1

data4CB when declared as var, it returns value 2 for all 3 iterations.

However, when data4CB is declared as let, it returns 0 in 1st iteration, 1 in 2nd and 2 in 3rd iteration.

Can you please explain this behavior ? I read let vs var but still unclear about this behavior. I tested this in Node.js and console of Chrome, and both showed the same behavior.

var lazyFunction = function(data4Lazy, cb){
  setTimeout(()=>{return cb(null, data4Lazy*4) },0)
}

for(let i = 0; i<3; i++){
  let data4Lazy =i;
  var data4CB=i

  lazyFunction(data4Lazy, (err,data)=>{
    if(err) console.log("code broke")
    //some processing on data = data+1
    console.log( "lazyFunction",data, data4CB)
  })    
}
jeff musk
  • 1,032
  • 1
  • 10
  • 31
  • variable declare with `let` only available to declaration context (scope) and variable declare with `var` can be access in whole context of program execution does this make sens? – uzaif Feb 18 '17 at 01:51
  • @uzaif is the scope of `let` limited to each iteration, and `let` variable in one iteration cannot be accessed from other iteration in `for` loop? – jeff musk Feb 18 '17 at 01:57
  • http://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example –  Feb 18 '17 at 02:02

0 Answers0