I'm working through a JavaScript tutorial. To show the difference between let and var, the following example is given, where it generates a bunch of boxes, and if you click on a box, it outputs the index of the box:
I created this codepen: https://codepen.io/run_the_race/pen/aXJQmp?editors=1111 The main part of interest is:
for (var i=0; i < 20; i++)
{
var div = document.createElement("div");
div.onclick = function() {
console.log("You clicked on box #:" + i);
}
document.querySelector("section").appendChild(div);
}
If one uses var to declare i, the same index value is shared between all the boxes. If one uses let to declare i, then the tutorial says i has block scope, so a different variable is created for each index.
Well my question is then, if i is a separate variable in each loop execution, how come if I increment i within the loop, it will change the number of iterations?
It appears to be separate for each iteration (not shared like when declared with var), but is shared because changing it affects the iterations. I understand what is happening, but I don't understand why.
Edit: Although the other posts address what the tutorial explained, they did not explain that for each iteration, i is declared again with the value of i at the end of the previous iteration, as @Pointy explained. I also simplified it a bit.