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

MySQL Query : SELECT * FROM `codeshelper`.`v9_news` WHERE status=99 AND catid='6' ORDER BY rand() LIMIT 5
MySQL Error : Disk full (/tmp/#sql-temptable-64f5-1b3e24f-e93d.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
MySQL Errno : 1021
Message : Disk full (/tmp/#sql-temptable-64f5-1b3e24f-e93d.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
Need Help?