How to use Recursion In Javascript
In a recursive approach a function repeatedly calls itself, taking the substring from the second character and concatenating it with the first character, until the base case is reached, reversing the string.
Example: This code implements the recursion to reverse a string in JavaScript.
function strReverse(str) {
if (str === "") {
return "";
} else {
return strReverse(str.substr(1)) + str.charAt(0);
}
}
console.log(strReverse("w3wiki"));
console.log(strReverse("JavaScript"));
console.log(strReverse("TypeScript"));
Output
skeeGrofskeeG tpircSavaJ tpircSepyT
Reverse a String in JavaScript
We have given an input string and the task is to reverse the input string in JavaScript. It is a very common question asked in a JavaScript interview. There are various methods to reverse a string in JavaScript, which are described below with examples.
Examples:
Input: str = "w3wiki"
Output: "skeeGrofskeeG"
Input: str = "Hello"
Output: "olleH"