0

I do not know how js engine handle the difference between two scripts below:

var a = [];
for (i = 0 ; i< 10 ; i++ ){
  var temp = {};
  var k = i;
  temp.test = function (){
    return k;
  }
  a.push(temp); 
}

for (i = 0 ; i<10 ;i++ ){
  console.log(a[i].test());
}

Output

999999999

var a = [];
for (i = 0 ; i< 10 ; i++ ){
  var temp = {};

  temp.test = function (){
    var k = i;  //<--------------------- this line is moved
    return k;
  }
  a.push(temp); 
}

for (i = 0 ; i<10 ;i++ ){
  console.log(a[i].test());
}

output 123456789

The output is from running the script in node.js

Sometime even bizarre: If the script is run in chrome, the output is both: 999999999

I think chrome and node.js all use V8 engine, why different?

GingerJim
  • 3,737
  • 6
  • 26
  • 36
  • 1
    You might also want to read [How do JavaScript closures work](http://stackoverflow.com/questions/111102/how-do-javascript-closures-work?rq=1) – thefourtheye Jul 14 '14 at 10:26
  • The post helps. But after reading it, I find my intuition is still against the result. if "var k = i" is outside the function definition, the k variable would be in a closure and still hang in each function definitions, so I would expect the result to be 123456789 not 999999999. – GingerJim Jul 14 '14 at 10:37
  • All the functions will get the reference of `k` and whenever they are called they will check the value of `k`. What do you think the value of `k` would be, when the loop is completed? – thefourtheye Jul 14 '14 at 10:41
  • I think I declare k in each loop by "var k", and the variable "i" is assigned to k by value in each loop. So each k seems to be completely different variables for each function declaration, that is why I am a bit confused. – GingerJim Jul 14 '14 at 10:46
  • No matter howmany times you define a variable in the current scope, it will be defined only once :-) Also, JavaScript doesn't have block scope but only function scope – thefourtheye Jul 14 '14 at 10:52
  • wow, so the k does not shadow each other. Thanks a lot. – GingerJim Jul 14 '14 at 10:55

0 Answers0