This is not a programming problem, it is just a question about a topic with scopes in JavaScript that I would like to understand better.
The following code loops through a serie of class elements and click on them at random interval rates between 250 and 750 ms. A very basic code but the curious (and most difficult thing to understand to me is the use of the let declaration for the i variable in the for loop.
var x2 = document.querySelectorAll(".someClass");
for (let i=0; i < 35; i++){
setTimeout(function(){
x2[i].click();
}, i*(Math.random()*(750-250) + 250));
}
Without the let, that is, if I would have used var instaad of let (and this either in the loop declaration, outside the loop or globally) the x[2] element would be undefined. If I create a new scope inside the loop, this code would not work as expected. Instead of clicking the x2[i] element with a random delay 35 times, it would first wait the random delay and then click all the elements at once.
But, as far as I know, the let declaration only means that the i variable would have a scope limited for the for loop. Why would using var make it undefined? And, if I wrap the call in another anonymous function to create a scope, which is counter-intuitive, the result would be a completely buggy behaviour. How all this is possible? Is that a design flag in JavaScript or is this a common fact in many other programming languages?
Am I missing anything?