I came across a snippet like this
(function(){
for(var i=0;i<3;i++){
setTimeout(function(){
console.log(i)
})
}
}())
I expected it to log 1,2.... instead it logged 3. Not sure if this is because js beign single threaded,& looking the queue only after finishing the loop.
WORKING COPY
It is because JavaScript executes in async
manner. When console.log(i)
was executing, the for loop
completed its iteration and as JavaScript does not have block level scope the value of i
in console.log(i)
became 3
for all the iterations.
A workaround for this is using IIFE and passing i
into the scope:
for (var i = 0; i < 3; i++) {
(function(i) {
setTimeout(function() {
console.log(i)
});
})(i);
}
Read More about IIFE
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With