iteration var vs let
by Shawn
HTML
<div id="using-var"></div>
<div id="using-let"></div>
<div id="using-alt"></div>
JavaScript
var divVar = document.getElementById("using-var"),
divLet = document.getElementById("using-let"),
divAlt = document.getElementById("using-alt");
var x = [], y = [], z = [];
for (var i=0; i<5; i++) {
x[i] = function() {
divVar.innerText+=i;
}
}
x.forEach(function(value){value();});
//let is recreated every iteration beginning with
//the previous iteration value, so when the
//increment occurs it happens where it left off
for (let i=0; i<5; i++) {
y[i] = function() {
divLet.innerText+=i;
}
}
y.forEach(function(value){value();});
//another way of thinking about it
//Thanks to David Walsh
//https://davidwalsh.name/for-and-against-let
{ let k;
for (k=0; k<5; k++) {
let i = k; // <-- new `i` for each iteration!
z[i] = function() {
divAlt.innerText+=i;
}
}
}
z.forEach(function(value){value();});