How to use Tail Recursion In Javascript
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
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