JavaScript Program to Reverse a String Using Recursion
We are given a string and the task is to reverse this string using the recursion technique in JavaScript such that a function calls itself again and again until it reaches the base case.
Table of Content
- Using Basic Recursion
- Using Tail Recursion
Using Basic Recursion
The function recursively divides the string into smaller substrings until a base case is reached, then concatenates the reversed substrings to form the reversed string.
Example: The below code example uses basic recursion to reverse a string using recursion in JavaScript.
function reverseString(str) {
// Base case
if (str === "" || str.length === 1) {
return str;
}
// Calling function recursively
return reverseString
(str.substring(1)) + str[0];
}
console.log(reverseString("w3wiki"));
console.log(reverseString("JavaScript"));
console.log(reverseString("GFG"));
Output
skeeGrofskeeG tpircSavaJ GFG
Using Tail Recursion
Similar to basic recursion but optimized for tail call optimization, which improves performance in some JavaScript engines.
Example: The below code example uses the tail recursion to reverse a string using recursion in JavaScript.
function reverseStringTailRecursion
(str, reversedStr = "") {
// Base case
if (str === "") {
return reversedStr;
}
// Tail recursive method call
return reverseStringTailRecursion
(str.substring(1), str[0] + reversedStr);
}
console.log(reverseStringTailRecursion("w3wiki"));
console.log(reverseStringTailRecursion("JavaScript"));
console.log(reverseStringTailRecursion("GFG"));
Output
skeeGrofskeeG tpircSavaJ GFG
Contact Us