Algorithm


Using JavaScript Native methods for reverse a string or number:

Steps:

  1. string.split("") is used to make an array first from the strings to characters array
  2. reverse() is used to reverse the array
  3. Then join("") is used to make a string again from the array by joining "".
string.split("").reverse().join("");

 

Using For Loop

Steps:

  1. Find last index of the string or array - string.length - 1;
  2. Initialize an empty reverse string - let reverseString = "";
  3. Start a for loop from last index to upto 0'th index
  4. Inside the loop, concat the reverseString
  5. 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

x
+
cmd
Akash

Output

x
+
cmd
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

x
+
cmd
["a", "b", "c"]

Output

x
+
cmd
["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

x
+
cmd
Akash

Output

x
+
cmd
hsakA
Advertisements

Demonstration


JavaScript - Reverse a String or Number or Array in various Ways

Previous
JavaScript Practice Example #3 - Assign 3 Variables and Print Good Way