1

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.)

juanli
  • 583
  • 2
  • 7
  • 19
  • All elements are not same funcs.push(function() { console.log(i); }); here i will be replaced with iterating value i.e. 0,1,2,3...9 so you will get var funcs = [function() {console.log(0)}, function() {console.log(1)}....function() {console.log(9)}]; and forEach will just execute all these functions one by one – Usman Wali Feb 15 '18 at 15:19

0 Answers0