Hey
for(let i = 0; i<3; i++) {
setTimeout(() => {
console.log(i);
})
}
Why this is return 0,1,2 I know If I change let to var this is return 3 times 3. But What is going with let. Actually first time I think every loop time I redeclared but I think this is not true. Someone can explain what is going on here?
Marco Alka
Software Engineer, Technical Consultant & Mentor
varis not block-scoped. Since thefor..-loop is sync, JS will first go through the loop three times, setting the timers, and then execute the timer handlers after the loop is finished.var iwill be changed on a global scope. In the end,iwill be3and once the timer handlers execute, that's what they print.letis block-scoped, so on every loop execution, new memory will be allocated and bound to the loop block (current scope) fori. Once the timer handler executes, it will access theiof the loop invocation it was created in for the timer, so you will actually access different memory locations for every timer handler and have different results.varandletare both valid options, depending on what you want to do. Most of the time, though,varis the un-intuitive option and not what you want, so I recommend defaulting toconst, and useletfor mutable variable bindings (like thefor...-loop in your question).Let me also recommend reading this Hashnode article, which describes the difference between var and let/const pretty well: