Open In App

JavaScript Program to Reverse a String Using Recursion

Last Updated : 10 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
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"));

// Nikunj Sonigara

Output
skeeGrofskeeG
tpircSavaJ
GFG

Using Stack

A stack can be used to reverse a string by pushing all characters of the string into the stack and then popping them off in reverse order.

Example:

JavaScript
function reverseStringUsingStack(str) {
    let stack = [];
    // Push all characters to stack
    for (let i = 0; i < str.length; i++) {
        stack.push(str[i]);
    }
    // Pop all characters from stack and form the reversed string
    let reversedStr = "";
    while (stack.length > 0) {
        reversedStr += stack.pop();
    }
    return reversedStr;
}

console.log(reverseStringUsingStack("GeeksforGeeks"));
console.log(reverseStringUsingStack("JavaScript"));
console.log(reverseStringUsingStack("GFG"));

// Nikunj Sonigara

Output
skeeGrofskeeG
tpircSavaJ
GFG

Next Article

Similar Reads