I am relatively new to JavaScript and i can’t wrap around my head on how this code is executing
function foo(i) {
if (i < 0) {
return;
}
console.log(`begin: ${i}`);
foo(i - 1);
console.log(`end: ${i}`);
}
foo(3);
the output of this code is
begin: 3
begin: 2
begin: 1
begin: 0
end: 0
end: 1
end: 2
end: 3
According to my understanding after all logs of begin statement, only one log with end statement should get printed that too with -1 value
begin: 3
begin: 2
begin: 1
begin: 0
end: -1
As I gets decremented from 0
by -1
, the if statement condition becomes true and returns the flow to next line of recursive function and prints end: -1
and ends the program.
I have an intuition that this might be a silly question but I still want to know where am I lacking. Help would be appreciated
3
Answers
i
is not decremented, the valuei-1
is passed as the value whenfoo
is recursively called. When the value passed intofoo
is -1, it returns before anything is console logged, and goes up a level to wherei
is 0.console.log(`end: ${i}`);
prints out that value, and then the function implicitly returns up to the next level wherei
is 1. And so on from there.The flow is like this
When you call a function, you don’t enter that function’s definition. You enter that function definition’s copy.
Each invocation of a function is separate. It doesn’t matter what’s the name of that function. Whether it’s the same name of some other name — each invocation is new. It copies the corresponding definition, and works on the fresh copy.
Imagine you call
foo(1)
in your example. Then your snippet is the same asYou are probably not surprised that these
i_nnn
s in these different functions do not interfere with each other. But it’s the same thing even with the same functionfoo
called everywhere instead of thesefoo_nnn
s. Because each call tofoo
copies the same definition and works on the new, fresh copy of it, as if it got a new namefoo_nnn
like here above, working on its own set of its inner variablesi_nnn
.So then it is non-surprising that the above execution proceeds as
which is
and this is the same as
and this is the same as
Now, replace all
foo_nnn
in the above withfoo
.Nothing changes.