Why incrementor is printing 3 even condition is checking for less then 3? [duplicate]


Why incrementor is printing 3 even condition is checking for less then 3? [duplicate]



This question already has an answer here:



for below code output will print "3" for 3 times, i.e updates same variable for 3 times


for(var k=0;k<3;k++){
setTimeout(()=>{
console.log(k)
},1000)
}



similarly if i use let instead of var 1,2,3


for(var k=0;k<3;k++){
setTimeout(()=>{
console.log(k)
},1000)
}



i know why it prints 0,1,2 as i is different every time. i'm just wondering why its printing 3 in case of var as condition is to checking for less then 3?



This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.





read this github.com/getify/You-Dont-Know-JS/blob/master/…
– Tiep Phan
Jun 30 at 6:52





and this github.com/getify/You-Dont-Know-JS/blob/master/…
– Tiep Phan
Jun 30 at 6:53





you have pasted the exact same code in both snippets.
– Oerd
Jun 30 at 6:58





please have a look to duplicate target 2 and 3
– Nina Scholz
Jun 30 at 7:32




2 Answers
2



The above result is because, var defines variable globally, or locally to an entire function regardless of block scope.



let creates a variable declaration for each loop which is block level declaration. So basically it creates a scope within { }.



If you want to print using var keyword use self invoked functions :



for(var k=0;k<3;k++){



(function(k){


setTimeout(()=>{

console.log(k)

},1000)

})(k);



}



the function setTimeout will execute after the delay provided. The code execution doesn't stop since the javascript is based on concurrency model and event loop, so the execution continues till the delay provided. which in case, increment the k. Also, the post-increment operator will use the value before iteration. So, for last iteration the value of k is 3, but since we have given a delay, it would print 3 every time.


setTimeout

Popular posts from this blog

Render GeoTiff to on browser with leaflet

How to get chrome logged in user's email id through website

using states in a react-navigation without redux