Open In App

JavaScript Program to Reverse a String Using Recursion

Last Updated : 12 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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.

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.

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("GeeksforGeeks"));
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.

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("GeeksforGeeks"));
console.log(reverseStringTailRecursion("JavaScript"));
console.log(reverseStringTailRecursion("GFG"));

Output
skeeGrofskeeG
tpircSavaJ
GFG

Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads