0

When I call a recursive on function, where do the results of the call go?

function reverse(str){ 
    if (str.length == 1){ 
      return str;
    } 
  rev = reverse(str.substr(1)) + str.charAt(0);
}

reverse("String"); 
console.log(rev); // ----> "undefinedS" - Only the last call is saved.

If I just return the value it seems fine. Where is the result getting stored?

function reverse(str){ 
    if (str.length == 1){ 
      return str
    } 
  return reverse(str.substr(1)) + str.charAt(0);
}

reverse("String") // ----> "gnirtS"
5
  • 1
    It isn't getting stored anywhere, if you don't have a return in a function it'll run until complete and the return value will be undefined Commented Apr 24, 2018 at 19:47
  • 2
    Here's a hint: Without returning anything, the call to reverse will return undefined. So you get undefinedS because you're concatenating undefined (the result of reverse(str.substr(1))) and S (the result of str.charAt(0)). Commented Apr 24, 2018 at 19:48
  • it is not undefined ...it is undefinedS the first operation results. Commented Apr 24, 2018 at 19:48
  • 1
    There's a difference between what the function returns and what you assign to the global variable rev. Commented Apr 24, 2018 at 19:49
  • Your function is not returning anything therefore on your second call, it will return undefined, which is why you get undefinedS Commented Apr 24, 2018 at 19:50

2 Answers 2

2

Your first version

rev is stored in the global namespace, and is overwritten each time the function reverse is called.

The recursion stops when the string's length is one, after having taken only the last n-1 characters. As a result, the final character is the only character in the string, S, and that is what str.charAt(0) gives.

Since the function reverse does not return a value when str is length 0 (which is what happens with "S".substr(1)) the value of reverse(str.substr(1)) is undefined.

This results in undefinedS.

Your second version

This version creates a call stack whereby the string is slowly taken apart by n-1 (where n is its length) until its length is 1. At that point the stack is unwound, causing each letter from the last to the first to be returned. Each function call as its own Execution context, whereby a Variable Environment is holding the value of each string.

The result of the callstack unwinding is gnirtS.

Sign up to request clarification or add additional context in comments.

Comments

0

Cleaner Look code

function reverse(str){ 
   return (str.length == 1)? str : reverse(str.substr(1)) + str.charAt(0);
}

1 Comment

Or by arrow function :) var reverse = str => (str.length == 1)? str : reverse(str.substr(1)) + str.charAt(0);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.