How recursive function is returning value?

Viewed 98
function reverse(str){
    if(str.length <= 1) {
        return str;
    } 
    return reverse(str.slice(1)) + str[0];
}

console.log(reverse("two"))

When the last return str line hits inside the if statement, it returns 'o'. Yet there is an extra + str[0] outside the if statement. Shouldn't it be returning 'oo' rather than 'o'?

The function is working completely fine, but when I try to visualize it I get confused.

3 Answers

A visual representation of the code. enter image description here

It will enter the if branch only when the string length is less than or equal to 1

eg. str = "o"

then it will enter

if(str.length <= 1) {
    return str; //here your function will return the answer to main() and will exit this function
} 

OUTPUT

o

Since you are writing return str it will immediately return from that function and will not execute any following lines of code. So it will not execute this:

return reverse(str.slice(1)) + str[0]; //this part will never be reached

The above part will be executed only if the str len>=2


Let us now understand the recursion stack

str  =  "two"

This is how recursion works--

reverse(two) = reverse(wo)+ t = reverse(o)+ wt = o+wt = owt

Note : reverse(o) will simply return o as length of string is 1

This is how it happens in order of the function's internal behavior:

  1. reverse('two') is called
  2. reverse('two') calls reverse(str.slice(1)) which evaluates to a call to reverse('wo')
  3. reverse('wo') calls reverse(str.slice(1)) which evaluates to a call to reverse('o')
  4. if(str.length <= 1) evaluates to true and the the reverse('o') call returns 'o' to the caller
  5. The reverse('wo') call returns 'ow' to the caller (str[0] was 'w')
  6. The reverse('two') call returns 'owt' to the caller (str[0] was 't')

and the final result is 'owt', as expected.

So in

return reverse(str.slice(1)) + str[0];

str[0] will not be added to reverse(str.slice(1)) until the function call returns. and when it returns the value of str[0] will be the value it was when reverse(str.slice(1)) was called.

When the if statement is satisfied and evaluates to true it exits the current function call immediately returning the value 'o' to the caller, since there is a return statement inside the if.

if(str.length <= 1) {
    return str;       // <-- exits here and returns 'o'
}
Related