In the mdn docs it gives an example in which functions are initialized in the for loop initialization block
for (
let i = 0, getI = () => i, incrementI = () => i++;
getI() < 3;
incrementI()
) {
console.log(i);
}
// Logs 0, 0, 0
It gives the following explanation of why this occurs:
This logs "0, 0, 0", because the i variable in each loop evaluation is actually a separate variable, but getI and incrementI both read and write the initial binding of i, not what was subsequently declared.
For each iteration we get a new i
in the for loop body. The i
variable in the initialization block is also in the scope of the for loop body.
I am hoping someone can explain this a bit better than what mdn did, I am having a bit of a hard time grasping what is going on here since there is a closure here, the i
variable belongs to the scope of the for loop body, and when I add a debugger statement to getI
or incrementI
everything looks as one might expect, just inside the for loop body it doesn't seem to see it and it logs 0 each iteration.