0

why it is printing 11 eleven times?this code is printing 0,1,2,3,4 ....10, while i is declared using let. But why it is printing 11 while i is decalred using var. why it is printing 11 inside setTimeout()


for(var i = 0; i<= 10; i++){
    console.log(i);
    setTimeout(function(){
        console.log(i);
        },0);
}
  • It is because of the block scope of `var`, change it to `let`. More details here: https://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example – annes Jul 22 '23 at 08:43

0 Answers0