Using let, in for Loop Why is the I value not added once after the end of the last loop

var testVar;
for(var i=0;i<3;iPP){
    testVar=function(){
    console.log(i)
    };
}
testVar(); // 3
let testVar;
for(let i=0;i<3;iPP){
    testVar=function(){
    console.log(i)
    };
}
testVar(); // 2
A reference to I is saved in the closure in

testVar, instead of the current value of I, and the value of I is iPP to 3 after the end of the last loop.
but let"s for loop, the last loop, should also hold a reference to I, and this I should also be executed once after the end of the last loop, and the iPP, should also become 3. But why the output is 2.
because of the different understanding of closures, which is not the focus of this issue, I asked the question again in a different way, as follows-
testVar () returns the I value of this function when it is called, using the for loop of var, and the last loop I value is 2. Because the loop has ended when it is called, the I value needs to be iPP,. So it becomes 3;
and let"s for cycle, theoretically speaking, is also the same process, and finally we have to do iPP,. Why is it still 2?

Mar.14,2021

var's for loop I understand

No, you don't understand

your code is equivalent to:

The difference between
  

is that let creates a block-level scope every time the program enters the curly braces, so the printed I is the last value of I in this loop, which is inaccessible outside the loop.
and using var results in variable declaration promotion, so the printed I is the last global iPerson3.

Menu