JavaScript variable binding and loop

Not really anything more than the two ways that you have proposed, but here’s another

for(var it = 0; it < 2; it++)
{
    (function() {
        var m = it;   
        setTimeout(function() {
            alert(m);
        }, 1);
    })(); 
}

Essentially, you need to capture the variable value in a closure. This method uses an immediately invoked anonymous function to capture the outer variable value it in a local variable m.

Here’s a Working Demo to play with. add /edit to the URL to see the code

Leave a Comment