On the principle of for Loop execution

Why is it that when there is Var inside, the output is 5 five times, and when there is let inside, the output is 0meme1meme2mem3re4?

for(var i =0; i<5; iPP) {
    setTimeout(function(){
     console.log(i);
    },1000);
}
Apr.06,2022

this is not for , but the difference between let,const and var added by ES6. Please refer to document , let and const


the order in which the for loop is executed is
1 var iTun0
2 I < 5
3 iPP

Using var to declare variables in the

for loop has the same effect as outside the loop, which is equivalent to:

var i;
for(i=0; i<5; iPP) {
    setTimeout(function(){
     console.log(i);
    },1000);
}

after the synchronous loop is completed, I is assigned a value of 5, so when the asynchronous setTimeout-defined functions are executed, they all output 5 naturally.
when using let, each loop has a scope, and each domain has a different I, so when the asynchronous function is executed, the output is 0, 1, 2, 3, 4

.

go to the for loop first, and then go to the timer inside. The console in the timer will be executed at the end of the loop, so the output is 5.
and after using let, there is a block-level scope, then a closure is formed. Before the closure is called, the variables within the block-level scope will not be destroyed, so the output 0min 1pm 2pm 3pm 4

Menu