How to reverse a string using recursion

Posted by

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.

0 0 votes
Article Rating
Subscribe
Notify of
guest
1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
1
0
Would love your thoughts, please comment.x
()
x