How to use Basic Recursion In Javascript

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

Output
skeeGrofskeeG
tpircSavaJ
GFG

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

Similar Reads

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....

Using Tail Recursion

Similar to basic recursion but optimized for tail call optimization, which improves performance in some JavaScript engines....