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