JavaScript Program to Reverse String Using Recursion
function reverseString(str) { if (str === "") return ""; return reverseString(str.slice(1)) + str[0]; } which calls itself with the string minus the first character and adds the first character at the end.Examples
How to Think About It
Algorithm
Code
function reverseString(str) { if (str === "") { return ""; } return reverseString(str.slice(1)) + str[0]; } console.log(reverseString("hello"));
Dry Run
Let's trace reversing the string "abc" through the code.
Initial call
reverseString("abc") calls reverseString("bc") and will add 'a' later.
Second call
reverseString("bc") calls reverseString("c") and will add 'b' later.
Third call
reverseString("c") calls reverseString("") and will add 'c' later.
Base case
reverseString("") returns "" because the string is empty.
Returning from third call
reverseString("c") returns "" + 'c' = "c".
Returning from second call
reverseString("bc") returns "c" + 'b' = "cb".
Returning from initial call
reverseString("abc") returns "cb" + 'a' = "cba".
| Call | Input String | Returned Value |
|---|---|---|
| 1 | "abc" | reverseString("bc") + 'a' |
| 2 | "bc" | reverseString("c") + 'b' |
| 3 | "c" | reverseString("") + 'c' |
| 4 | "" | "" (base case) |
| 3 | "c" | "c" |
| 2 | "bc" | "cb" |
| 1 | "abc" | "cba" |
Why This Works
Step 1: Base case stops recursion
When the string is empty (""), the function returns an empty string to stop further calls.
Step 2: Recursive call reduces problem size
The function calls itself with the string minus the first character (str.slice(1)), making the problem smaller each time.
Step 3: Building reversed string on return
After the recursive call returns, the first character of the current string (str[0]) is added to the end, gradually building the reversed string.
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 reverseStringBuiltIn(str) { return str.split("").reverse().join(""); } console.log(reverseStringBuiltIn("hello"));
Complexity: O(n) time, O(n) space
Time Complexity
The function calls itself once per character, so it runs in linear time relative to the string length.
Space Complexity
Each recursive call adds a new layer to the call stack, so space used grows linearly with string length.
Which Approach is Fastest?
The loop and built-in methods are faster and use less memory than recursion because they avoid call stack overhead.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Recursion | O(n) | O(n) | Learning recursion and problems naturally recursive |
| Loop | O(n) | O(1) | Efficient string reversal in practice |
| Built-in functions | O(n) | O(n) | Quick and concise code |