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)
})
}