Here is the code.
print(5);
function print(n) {
if (n == 0) {
return;
}
print(n - 1); //call function recursively
console.log(n);
}
I would expect after the return statement that console.log(n) would output zero (0)because that was the value of n when I called the return statement. Instead it returns 1 - 5 ??? Return was only called once, so can anyone explain what is going on here?
Within your code there is an implicit return, think of the function more like this:
function print(n){
if(n==0){
return ;
}
print(n-1); //call function recursively
console.log(n);
return undefined;
}
So when print(n-1) is called with 4 it'll recurse down until you get to you're value of 0. After that however, the calling function will log the n value.
Essentially your return only returns to the caller, it doesn't completely unwind the callstack and prevent that console.log being called. It'll look something like this:
print(n-1); // called with 4
print(n-1); // called with 3
print(n-1); // called with 2
print(n-1); // called with 1
print(n-1); // called with 0
return;
console.log(n) // 1
console.log(n) // 2
console.log(n) // 3
console.log(n) // 4
console.log(n) // 5
The print function is still called five times. The value of n does not propagate to the earlier calls.
The return statement does not end the whole chain of recursive calls. Execution proceeds after the return statement in the line where the exiting function was called.
If you want some code to be executed only once in a recursive function, put it before the return in the if branch:
function print(n) {
if (n == 0) {
console.log(n);
return;
}
print(n - 1); //call function recursively
}