The let statement is advocated for usage in for
loops as replacement for var
declaration of the iteration variable.
By using let
the user can forgo the usage of immediate invocation function
to preserve the value of iteration variable for callbacks for instance.
From mdn:
var list = document.getElementById('list');
for (let i = 1; i <= 5; i++) {
let item = document.createElement('li');
item.appendChild(document.createTextNode('Item ' + i));
item.onclick = function(ev) {
console.log('Item ' + i + ' is clicked.');
};
list.appendChild(item);
}
// to achieve the same effect with 'var'
// you have to create a different context
// using a closure to preserve the value
for (var i = 1; i <= 5; i++) {
var item = document.createElement('li');
item.appendChild(document.createTextNode('Item ' + i));
(function(i){
item.onclick = function(ev) {
console.log('Item ' + i + ' is clicked.');
};
})(i);
list.appendChild(item);
}
If I update the iteration variable i
at the end of the loop, the for
structure will pick it up and use the new value in the comperator logic of the loop and transfer that value to the next execution of the block.
console.log("start");
for (let i = 0; i < 5; i++) {
console.log("in loop", i);
setTimeout(function () {
console.log(i);
}, 0);
i = i + 2;
}
console.log("end");
Results:
start
in loop 0
in loop 3
end
undefined
2
5
The changes in the second iteration, do not propagate to the first iteration timeout callback.
Currently I thing the for
loop implementation create a block execution context for each iteration, transfer the iteration variable as param, and specifically extract its value after the execution of the block ends and use it in the for
mechanism for the next iteration. But it would be interesting to know if this is true, or not, and how it is implemented.