Reverse a String
Program to reverse a string
JavaScript Reverse a String Program
This program helps you to learn the fundamental structure and syntax of JavaScript programming.
// Method 1: Using split, reverse, join
let str = "Hello";
let reversed = str.split('').reverse().join('');
console.log("Original:", str);
console.log("Reversed:", reversed);
// Method 2: Using for loop
function reverseString(str) {
let reversed = '';
for (let i = str.length - 1; i >= 0; i--) {
reversed += str[i];
}
return reversed;
}
console.log("\nUsing loop:", reverseString("World"));
// Method 3: Using for...of loop
function reverseStringForOf(str) {
let reversed = '';
for (let char of str) {
reversed = char + reversed;
}
return reversed;
}
console.log("Using for...of:", reverseStringForOf("JavaScript"));
// Method 4: Using reduce
function reverseStringReduce(str) {
return str.split('').reduce((acc, char) => char + acc, '');
}
console.log("Using reduce:", reverseStringReduce("Programming"));
// Method 5: Using recursion
function reverseStringRecursive(str) {
if (str.length <= 1) return str;
return reverseStringRecursive(str.slice(1)) + str[0];
}
console.log("\nUsing recursion:", reverseStringRecursive("Hello"));
// Method 6: Using spread operator
let reversed2 = [...str].reverse().join('');
console.log("Using spread:", reversed2);Original: Hello Reversed: olleH Using loop: dlroW Using for...of: tpircSavaJ Using reduce: gnimmargorP Using recursion: olleH Using spread: olleH
Understanding Reverse a String
This program demonstrates different methods to reverse a string.
Method 1: Split, Reverse, Join
Most common approach:
str.split('').reverse().join('');
Steps:
split(''): String → Arrayreverse(): Reverse arrayjoin(''): Array → StringMethod 2: For Loop
Iterate backwards:
for (let i = str.length - 1; i >= 0; i--) {
reversed += str[i];
}
Method 3: For...Of Loop
Prepend each character:
for (let char of str) {
reversed = char + reversed;
}
Method 4: Reduce
Functional approach:
str.split('').reduce((acc, char) => char + acc, '');
How it works:
Method 5: Recursion
Recursive approach:
if (str.length <= 1) return str;
return reverseStringRecursive(str.slice(1)) + str[0];How it works:
Method 6: Spread Operator
ES6 syntax:
[...str].reverse().join('');
Spread vs Split:
Time Complexity:
When to Use:
-
Split/reverse/join
: Simplest, most common
-
Loop
: Learning, custom logic
-
Reduce
: Functional style
-
Recursion
: Learning recursion
Let us now understand every line and the components of the above program.
Note: To write and run JavaScript programs, you need to set up the local environment on your computer. Refer to the complete article Setting up JavaScript Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your JavaScript programs.