Reputation: 99
I have confusion on function recursion
function foo(i) {
console.log("checking: " + i);
if (i < 0)
return;
console.log('begin: ' + i);
foo(i - 1);
console.log('end: ' + i);
}
foo(1);
why is the output:
checking: 1
begin: 1
checking: 0
begin: 0
checking: -1
end: 0
end: 1
it should not print the end: 0, end: 1, because we are returning in if condition. What is happening?
Upvotes: 2
Views: 42
Reputation: 370789
return
only terminates the most immediately running function.
foo(1)
foo(0)
foo(-1)
The
if (i < 0)
return;
gets fulfilled on the third call, terminating the third function
foo(1)
foo(0)
foo(-1) <-- this function stops running
but leaving the other functions to continue as normal:
foo(1)
foo(0) (execution resumes here, just after the foo(1) line)
It's possible to get out of all ancestor functions (up until a .catch
, if any) by throwing an error, but such a strategy just for the sake of control flow isn't a great idea.
function foo(i) {
console.log("checking: " + i);
if (i < 0)
throw new Error();
console.log('begin: ' + i);
foo(i - 1);
console.log('end: ' + i);
}
foo(1);
Upvotes: 4