for (var i = 0; i < 5; i++) {
var btn = document.createElement('button');
btn.appendChild(document.createTextNode('Button ' + i));
btn.addEventListener('click', function(){ console.log(i); });
document.body.appendChild(btn);
}
In the above code - the output will be 5 always no matter what button is pressed because I understand in js it is by referene, by the time the loop completed the final value will be updated in to 'i' - but 1 question I have is why 5 - I thought it is 4 - once the value of i is 4 shouldn't it come out of the loop?? Am I missing some understanding with 'for' loops?