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"
returnin a function it'll run until complete and the return value will be undefinedreversewill returnundefined. So you getundefinedSbecause you're concatenatingundefined(the result ofreverse(str.substr(1))) andS(the result ofstr.charAt(0)).rev.undefined, which is why you getundefinedS