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?