Scope

Iterating function expressions

by Charlie Winfrey

JavaScript

// Iterating with a function expression 
// can cause issues due to scope misuse
 
for (var i=0; i<3; i++) {
    setTimeout(function(){
        console.log(i);
    }, 1000*i);
} /**/// what will this output?

// Make a scope so the inner function
// can continue to access the variable you want
/*
for (var i=0; i<3; i++) {
    (function(){
        var j = i; // maintains state for each iteration
        setTimeout(function(){
            console.log(j);
        }, 1000*i);
    })();
}/**/

// We can refactor that a bit...
/*
for (var i=0; i<3; i++) {
    (function(i){
        setTimeout(function(){
            console.log(i);
        }, 1000*i);
    })(i);
} /**/