JavaScript Program to Reverse a String
split('') to turn it into an array, then reverse() the array, and finally join('') it back into a string like this: const reversed = str.split('').reverse().join('');Examples
How to Think About It
Algorithm
Code
const reverseString = str => str.split('').reverse().join(''); const input = 'hello'; const output = reverseString(input); console.log(output);
Dry Run
Let's trace the string 'hello' through the code
Input string
str = 'hello'
Split into array
['h', 'e', 'l', 'l', 'o']
Reverse array
['o', 'l', 'l', 'e', 'h']
Join array to string
'olleh'
| Step | Array State |
|---|---|
| After split | ['h', 'e', 'l', 'l', 'o'] |
| After reverse | ['o', 'l', 'l', 'e', 'h'] |
Why This Works
Step 1: Splitting the string
Using split('') breaks the string into an array of single characters so we can reorder them.
Step 2: Reversing the array
The reverse() method flips the order of elements in the array, putting the last character first.
Step 3: Joining back to string
Finally, join('') combines the reversed array back into a single string without spaces.
Alternative Approaches
function reverseStringLoop(str) { let reversed = ''; for (let i = str.length - 1; i >= 0; i--) { reversed += str[i]; } return reversed; } console.log(reverseStringLoop('hello'));
function reverseStringRec(str) { if (str === '') return ''; return reverseStringRec(str.substr(1)) + str[0]; } console.log(reverseStringRec('hello'));
Complexity: O(n) time, O(n) space
Time Complexity
The code processes each character once when splitting, reversing, and joining, so it runs in linear time relative to string length.
Space Complexity
Extra space is used to store the array of characters and the reversed array, so space grows linearly with input size.
Which Approach is Fastest?
The built-in split-reverse-join method is usually fastest and most readable; loops are similar in speed but more verbose; recursion is slower and uses more stack space.
| Approach | Time | Space | Best For |
|---|---|---|---|
| split-reverse-join | O(n) | O(n) | Quick and readable code |
| for loop | O(n) | O(n) | Manual control, beginner-friendly |
| recursion | O(n) | O(n) | Learning recursion, less efficient |
split(''), reverse(), join('') for a quick and readable string reversal in JavaScript.