I am a little bit confused on the exact execution timeline in which the following function runs. I saw this code on the MDN guide:
function foo (i) {
if (i<0) return;
console.log('begin' + i);
foo(i-1);
console.log('end' + i);
}
Based on my knowledge of how functions work, this is what I thought, though my knowledge is inadequate:
I think when the function foo(3) is called, it will go to the function and check the condition if i < 0, then it will run the next code console.log('begin:' + i).
After that, the next line of code is executed, since JavaScript execute line by line, the next line of code which is foo(i-1) will be executed.
It takes the current value of i which is 3 minus 1, so foo(2) is called and the execution continues.
My question is: Is my understanding correct?. If no please explain what this code is doing, otherwise can anyone explain breiefly when will the function stop being called?
foo(3)begin 3 begin 2 begin 1 begin 0 end 0 end 1 end 2 end 3