+ 2
Why does the first loop print only 3?
14 ответов
+ 3
This is because the first for loop uses var and the second uses let. Var is function scoped and let is block scoped. What that translates to in this case is that the var loop will use whatever the current value of i is and the let loop will use the value of i for each iteration of the loop. This is why I always use let to declare index variables in loops.
+ 3
Karak10 yes, loops are done differently with let and var. This particular case demonstrates how the difference in scope can change the output. Change the first loop to let and see for yourself.
If there was no timeout, the outputs would be the same, but the timeout allows the loop to complete and for the function scoped loop (var) x progresses to 3 and the timeout uses it's current value when the timeout fires, in the block scoped loop (let) the value of x is conserved for each iteration. This can also be an issue if you're setting multiple event listeners with for loops.
+ 2
Karak10 i think that the 1s timeout you have gives doesn't stop the loop it keeps on running and finally when the x value goes to 3 then it outputs the values
+ 2
Mike Perkowski oooh
A new thing for me to learn
Great 👏👏
+ 2
Karak10 i mean that even if I increase the time even then it appears all together but i think that there should be a delay of the timeout for every output (I guess)
+ 1
Mike Perkowski check this if you know
+ 1
Karak10 i saw that while executing everything is normal but the timeout interferes
+ 1
Krish it has something to do with closures, I guess I need to learn how closures work better.
+ 1
Mike Perkowski so loops are done differently for let and differently for var? I was told it has something to do with closures, but I don't really undersrand how are closures involved to this behaviour.
+ 1
Karak10 and Mike Perkowski
I noticed one more thing that if I increase the value of timeout lets say 5000ms even then all the outputs appears together.
Why so?
+ 1
Krish nothing changes when I change the timeout to 5000ms, share your code if you want. I created a demonstration of how loops are treated with var and how they are treated with let, I'm not sure if I got it right or not, Mike Perkowski can tell us, here is the code:
https://code.sololearn.com/WgwRxAY2IHNq/?ref=app
+ 1
Karak10 yes that must be a reason
0
Krish why does it behave differently for var and different for let?
0
Krish the loop finishes incredibly fast, so all the timeouts activate at almost the same time, with a difference of milliseconds which is the reason they finish in order.