0

I have snippet below, where values become as array of functions. Each function contains a console.log(i); Where i was a local variable of the loop. However when i execute (values[1]()) the values array the console.log is printing the i values. I'm trying to understand how this is possible

var values = [];

for ( let i = 0; i < 2; i++ )
{

  values.push(function() {
    console.log(i);
  })

}
console.log(values);  /* output :  Array [function() {
    console.log(i);
  }, function() {
    console.log(i);
  }]*/

values[0](); // output: 0

values[1](); // output: 1





jack
  • 81
  • 6
  • This is called a closure. See the linked question above for an explanation. – Code-Apprentice Jan 20 '20 at 17:41
  • It's possible because the function *closes over* the `i` variable, and because you used `let`, there's a different `i` variable for each loop iteration. (If you'd used `var`, there would be just one and all the `console.log` statements would output the value `2`.) FWIW, I go into some detail about this -- specifically in regard to `let` in a `for` loop like that -- in my new book in Chapter 2. ;-) See my profile for links. – T.J. Crowder Jan 20 '20 at 17:42
  • I think this statement _"The genius is that in JavaScript a function reference also has a secret reference to the closure it was created in"_ from [link](https://stackoverflow.com/a/111111/12025408) clarifies the question i have – jack Jan 20 '20 at 23:01

0 Answers0