To reverse a string in JavaScript using recursion, you can follow these steps:
Verify whether the string contains one character or is empty. If so, give the string back. This is the recursion’s fundamental case. Return the string’s last character after invoking the function with the string without its last character if the string contains more than one character. The code that connects these actions is as follows:
function reverseString(str) {
if (str.length <= 1) { // step 1
return str;
}
return str.charAt(str.length - 1) + reverseString(str.slice(0, -1)); // step 2
}
let reversed = reverseString('hello');
console.log(reversed); // prints 'olleh'
To learn how this code functions, let’s go through an example. Let’s say we want to invert the word “hello” in our string. The if statement in step 1 is false since the function is invoked with the argument “hello,” so it moves on to step 2. The result of running the function with the string “hell” (which is the original string without its last character) is concatenated with the string’s last character, “o,” in step 2.

I’m Abhishek, a DevOps, SRE, DevSecOps, and Cloud expert with a passion for sharing knowledge and real-world experiences. I’ve had the opportunity to work with Cotocus and continue to contribute to multiple platforms where I share insights across different domains:
-
DevOps School – Tech blogs and tutorials
-
Holiday Landmark – Travel stories and guides
-
Stocks Mantra – Stock market strategies and tips
-
My Medic Plus – Health and fitness guidance
-
TrueReviewNow – Honest product reviews
-
Wizbrand – SEO and digital tools for businesses
I’m also exploring the fascinating world of Quantum Computing.
[…] https://www.devopsconsulting.in/blog/how-to-reverse-a-string-using-recursion/ […]