0
for(var a = 0; a<100; a++){
    setTimeout(()=>{
        if(a<100) console.log(a)
    })
}

the tutorial I see says that all the output will be 100, which is confirmed by me through experiment. But I don't understand why the result is like this.

First, I partly understand that it is because the setTimeout is an async function, and when it is executed, the var has been already changed to 100. But it makes confused that if the statement is true, is it possible to have some output like 98, 99 which are less than 100, because maybe when the setTimeout is executed, the for loop is not over yet, and the a is at some intermediate value.

Second, the tutorial says that if replace the var with the const, the output will be as expected. But... the inner function is still asynchronous, is there some closure mechanism that make the callback function get the right value?

  • 1
    *"when the setTimeout is executed, the for loop is not over yet"* – this can never be the case. setTimeout resolves *after* all other code has executed, it'll never start running while some other code is still being executed. See [JavaScript closure inside loops – simple practical example](https://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example) – Guy Incognito Mar 11 '23 at 09:12

0 Answers0