A classic javascript (closure) interview question

for(var i =0; i<10; i++) {
    setTimeout(function(){
        console.log(i);
    }, i);

}
//10 10times


for(let i =0; i<10; i++) {
    setTimeout(function(){
        console.log(i);
    }, i);

}
// 0 - 9


for(var i =0; i<10; i++) {
    setTimeout((function(j){
        console.log(j);
    })(i), i);

}
//0 - 9  because it's an immediately invoked function and this function returns null


for(var i =0; i<10; i++) {
    setTimeout((function(j){
        return function( ) {
            // it doesn't need to go out all the way to i to find the variable. 
            // it stores the value j the moment the outer function gets executed
            console.log(j);
        }
    })(i), i);

}
//0 - 9

Comments

Popular posts from this blog

All the pitfalls I met in the first month