I know I can use the let keyword here to get the desired outcome, but I would like to know why clicking on the div items alerts #5 for each div.
var div;
var box = document.getElementById('box');
for (var i = 0; i < 5; i++) {
div = document.createElement('div');
div.onClick = function() {
alert('this is box # ' + i);
}
box.appendChild(div);
}
<div id="box"></div>
When you assign the anonymous function to the click, it does not run its body. Its body of codes runs only when it is clicked so the first time i variable is used in the function it has already the value of 4. You need to evaluate current value of i while it is in the loop and place it in the function generated, by a function generating function. Otherwise it will take a reference to i and use its latest value always.