The code for (var x=...)
declares a single variable whose value changes, but which is closed over for each function created. All functions reference the same value, with its latest changes. Using slightly older code hopefully makes this more obvious:
var callbacks = [];
for (var i=0;i<5;++i) callbacks.push( function(){ console.log(i) } );
callbacks.forEach(function(func){ func() })
// Outputs "5" five times
The code for (let x=...)
declares a new variable each time the loop is run, so each function gets a new variable (and associated value). This is very convenient when creating callbacks, so you don't have to do the old trick of:
var callbacks = [];
for (let i=0;i<5;++i){
// Create an anonymous function and invoke it, passing in 'i'.
// Each time the function is run a *new* variable named 'n'
// is created and closed over by the function returned inside.
var cb = (function(n){ return function(){ console.log(n) }})(i);
callbacks.push(cb);
}
callbacks.forEach(function(func){ func() })
// Outputs "0","1","2","3","4"
And, for proof, here it is using let
:
var callbacks = [];
for (let i=0;i<5;++i) callbacks.push( function(){ console.log(i) } );
callbacks.forEach(function(func){ func() })
// Outputs "0","1","2","3","4"