My first question was about different consequences of using var
and let
keywords in initialization expression of for
loop header which is a common question on stackoverflow. I read some other similar questions and now I know what is the difference but what I'm trying to understand is why this happens? I need to know what happens under the hood when we use let
rather than var
in for
loop. So I thought up an explanation and want to know if It's correct and if not, what's the correct explanation?
1- The following code uses var
for i
:
let printNumTwo;
for (var i = 0; i < 3; i++) {
if (i === 2) {
printNumTwo = function() {
return i;
};
}
}
console.log(printNumTwo());
My explanation: when i
's value is 2 the if
block executes and inside loop's body, we create a function and save it’s reference into printNumTwo
variable. The function says return i
. Here because i
has been declared using var
keyword and is global so we have access to i
's value everywhere so the function's actual instruction is "return what is stored in i
" whenever printNumTwo
is called. So after calling printNumTwo()
what is currently in i
variable is printed to console which is the number after last update: 3.
2- The following code uses let
for i
:
let printNumTwo;
for (let i = 0; i < 3; i++) {
if (i === 2) {
printNumTwo = function() {
return i;
};
}
}
console.log(printNumTwo());
My explanation: when i
's value is 2 the if
block executes and inside loop's body, we create a function and save it’s reference into printNumTwo
variable. The function says return i
. Here because i
has been declared using let keyword and we don’t have access to it after for
statement scope finishes, so the current value of i
matters so the function's actual instruction is "returns the number 2" whenever it’s called. So after calling printNumTwo()
number 2 is printed to console.