# Reverse a String With Recursion

I’m recently figering this algorithm in freecodecamp, but I just stuck tin understand this code there;
After times of return how could str.charAt(0) works?

``````function reverseString(str) {
if (str === "") // This is the terminal case that will end the recursion
return "";

else
return reverseString(str.substr(1)) + str.charAt(0);
/*
First Part of the recursion method
You need to remember that you won’t have just one call, you’ll have several nested calls
Each call: str === "?"        	                  reverseString(str.subst(1))     + str.charAt(0)
1st call – reverseString("Hello")   will return   reverseString("ello")           + "h"
2nd call – reverseString("ello")    will return   reverseString("llo")            + "e"
3rd call – reverseString("llo")     will return   reverseString("lo")             + "l"
4th call – reverseString("lo")      will return   reverseString("o")              + "l"
5th call – reverseString("o")       will return   reverseString("")               + "o"
Second part of the recursion method
The method hits the if condition and the most highly nested call returns immediately
5th call will return reverseString("") + "o" = "o"
4th call will return reverseString("o") + "l" = "o" + "l"
3rd call will return reverseString("lo") + "l" = "o" + "l" + "l"
2nd call will return reverserString("llo") + "e" = "o" + "l" + "l" + "e"
1st call will return reverserString("ello") + "h" = "o" + "l" + "l" + "e" + "h"
*/
}
reverseString("hello");
``````

Imagine the call stack like a pile of document.
You start from the bottom piling “up” on top of each other.

``````reverseString("Hello");
``````

Will start is evaluation, and realise that it have to pile a new document on top since you are returning

``````reverseSting("ello") + "H"
``````

So all this document pile up until you have the one that actually returns a value and is not piling up more functions on the top.

So our employee start marking this document as “done” and keeping the returned function.
So from the top to the bottom you have all this functions that “piled” on top of each other + `char(0)`

or from the “top”:

``````""
"o"
"l"
"l"
"e"
"H"
``````

… or this is how I like to imagine it
But refer to the serious explanation on MDN on how a call stack works.

Hope it helps

1 Like

Finally understand this! Thank u so much!
Return from the last call to the first call, and it will be “olleh”;
I will go to check the “call stack”… lol