We have code like:
var numbers = [1,2,3]; for(var i in numbers){
setTimeout(function(){console.log(numbers[i]);
}, 0);
} //
//
//
Note:
1. function block doesn't create scope!
2. setTimeout function run after all the other code finished.
Therefore, before setTimeout get run, for block already exec 3 times and i was set to 2.
Once setTimeout get running, it prints out numbers[i] which is 3.
Now, we change the code to:
var numbers = [1,2,3]; for(var i in numbers){
(function(){
var j = i;
setTimeout(function(){
console.log(numbers[j]);
})
})();
} //
//
//
Note:
1. function does create new scope.
2. the (function(){})() run immedatly.
3. (function(){}) inside for block actually is closure which does remeber the local var value (in our case is var j).