I'm reading the article about functions on the MDN, and I reached the Recursive part but I don't understand the last part that talks about using the stack-like behavior.
The example is that one:
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
On that function, I understand when the begin
log is shown but I don't when the end
log is shown. Can someone help me and explain it me?
Recursive functions use something called “the call stack.” When a program calls a function, that function goes on top of the call stack. This is similar to a stack of books. You add things one at a time. Then, when you are ready to take something off, you always take off the top item.
Recursion can potentially consume more memory than an equivalent iterative solution, because the latter can be optimized to take up only the memory it strictly needs, but recursion saves all local variables on the stack, thus taking up a bit more than strictly needed.
In some languages, your infinite recursive function will halt with a stack overflow based on system- or language-dependent conditions. The reason for this is that many implementations of function call and return allocate new space for each function call, and when space is exhausted the program will fail.
Each recursive function calls itself until hitting the base. Then, when the case becomes true, the result floats back to the top of the call stack, a list in the computer that keeps track of all the functions called in a program.
So basically on each call to foo while it does the i-1
it keeps the function open, it hasn't returned. It keeps going hence the begin keeps getting called, once it reaches 0 the last function call returns. Once this happens the other foo calls can start finishing as well. They will finish from oldest to newest.
You can see a visulization of this using loupe by Philip Roberts. Here is a Loupe of your example.
The best way to see it is probably to 'unfold' recursion and write it as sequence of consecutive calls:
foo(3);
begin:3
foo(2);
begin:2
foo(1);
begin:1
foo(0);
begin:0
foo(-1);
return;
end:0
end:1
end:2
end:3
'end:' strings are printed after reaching deepest recursion
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With