Regarding the let Declarations in loops in book Definitive JavaScript Developer guideline, the code:
var funcs = [];
for (let i = 0; i < 10; i++) {
funcs.push(function() {
console.log(i);
});
}
funcs.forEach(function(func) {
func(); // outputs 0, then 1, then 2, up to 9
})
It says:
The let declaration creates a new variable i each time through the loop, so each function created inside the loop gets its own copy of it. Each copy of i has the value it was assigned at the beginning of the loop iterations in which it was created..
I want to know, when invoke the function func()
, how and where it finds the i
value for each element in array of funcs
. All element in funcs
are same
ƒ () {
console.log(i);
}
Could someone illustrate how each step happens when call the function in the above code? (I sort of understand that, if use var
instead of let
, the global variable i
is what each call finds.)