Algorithm
Using JavaScript Native methods for reverse a string or number:
Steps:
string.split("")
is used to make an array first from the strings to characters arrayreverse()
is used to reverse the array- Then join("") is used to make a string again from the array by joining "".
string.split("").reverse().join("");
Using For Loop
Steps:
- Find last index of the string or array -
string.length - 1;
- Initialize an empty reverse string -
let reverseString = "";
- Start a for loop from last index to upto 0'th index
- Inside the loop, concat the reverseString
- Return reverseString
Only array reverse in JS
array.reverse();
Code Examples
#1 Code Example with Javascript Programming
Code -
Javascript Programming
const name = "Akash";
console.log(name.split("").reverse().join("")); // hsakA
Copy The Code &
Try With Live Editor
Input
Akash
Output
hsakA
#2 JavaScript Reverse an array using For loop in javascript
Code -
Javascript Programming
const array = ["a", "b", "c"];
const lastIndex = array.length - 1;
const reverseArray = [];
for(let i = lastIndex; i >= 0; i--){
reverseArray.push(array[i]);
}
console.log(reverseArray); // ["c", "b", "a"]
Copy The Code &
Try With Live Editor
Input
["a", "b", "c"]
Output
["c", "b", "a"]
#3 JavaScript Reverse an string using For loop in javascript
Code -
Javascript Programming
const string = "Akash";
const lastIndex = string.length - 1;
let reverseString = "";
for(let i = lastIndex; i >= 0; i--){
reverseString += string[i];
}
console.log(reverseString); // hsakA
Copy The Code &
Try With Live Editor
Input
Akash
Output
hsakA
Demonstration
JavaScript - Reverse a String or Number or Array in various Ways