Javascript variable copy scope

Viewed 1868

I have two blocks of code which I believe should produce the same result:

1.

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

2.

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

However, as most of you might expect, the first one log 9 ten times, and the second one log correctly from 0 to 9.

The second one is using closure to preserve the value of i. I think the first one should preserve the value as well, because:

  1. the var j create a new variable j in each iteration.
  2. current i value is assigned to this new j in the iteration.
  3. this new j is then bound to the setTimeout's function in the same iteration.
  4. next iteration will bind a new j to the function in that iteration.

But it turns out that the j is bound to the last i value for all iteration.

So, whats the differences between creating a variable using function argument and var ?

Please point out any mistake ! Thanks in advance !


Thank you all ! I did not know that javascript only has function and global scope ! Blame the other languages who taught me to do so :P

5 Answers
Related