Below is an example from MDN Function scope. I can not understand how the end: 0 and the rest of end: are printed. I was expecting that the console.log("end: " + i); will never be reached.
function foo(i) {
if (i < 0) return;
console.log("begin: " + i);
foo(i - 1);
console.log("end: " + i);
}
foo(3);
Output:
begin: 3
begin: 2
begin: 1
begin: 0
end: 0
end: 1
end: 2
end: 3
foo()is a call to itself (making this a recursive function). Everything after that call does not execute until the if condition becomes true and returns. The stack unwinds and now calls everything after the internalfoo()executes. It is extremely important to make sure recursive functions have a terminating condition.console.log("end: " + i);will never be reached. - why would you think that? it's just the next step, which is not conditioned on anything