Great question! There are several ways to reverse a string in JavaScript. Let me show you:
Method 1: Using built-in methods (Most common)
function reverseString(str) {
return str.split('').reverse().join('');
}
console.log(reverseString("hello")); // "olleh"
How it works:
split('') - converts string to array of characters
reverse() - reverses the array
join('') - joins array back to string
Method 2: Using a for loop (Your approach, fixed)
function reverseString(str) {
let reversed = "";
for (let i = str.length - 1; i >= 0; i--) { // Start at length - 1!
reversed += str[i];
}
return reversed;
}
The bug in your code: you started at str.length but should start at str.length - 1 because array indices are 0-based.
Method 3: Using reduce (Functional approach)
function reverseString(str) {
return [...str].reduce((rev, char) => char + rev, '');
}
Method 4: Using recursion
function reverseString(str) {
if (str === "") return "";
return reverseString(str.substr(1)) + str[0];
}
Performance Tip: For very long strings, the for loop method is fastest because it avoids creating intermediate arrays.
Hope this helps!