I don’t understand how all those f() function work, can someone explain why it prints two ‘1’, I know it prints ‘1’ for every ‘()’ after f(f), but I don’t know why.
JavaScript
x
9
1
function f(y) {
2
let x = y;
3
var i = 0;
4
return () => {
5
console.log(++i);
6
return x(y);
7
};
8
}
9
f(f)()();
And why does the ‘i’ doesn’t increase?
Thank you.
Advertisement
Answer
JavaScript
1
10
10
1
function f(y) {
2
let x = y;
3
var i = 0;
4
return () => {
5
console.log(++i);
6
return x(y);
7
};
8
}
9
f(f)()();
10
is equivalent to
JavaScript
1
11
11
1
function f() {
2
var i = 0;
3
return () => {
4
console.log(++i);
5
return f();
6
};
7
}
8
const t1 = f();
9
const t2 = t1();
10
t2();
11
is equivalent to
JavaScript
1
11
11
1
function f() {
2
var i = 0;
3
return () => {
4
console.log(++i);
5
};
6
}
7
const t1 = f();
8
t1();
9
const t2 = f();
10
t2();
11
If you did call each of t1
or t2
multiple times instead of just once, you’d increment the i
from the respective closure some more. But if you instead just chain them, they call f
again and initialise a new var i = 0
for a different closure.