Basically it's the different scope of var
with respect to let
, here You can find documentation of it in Spanish.
Now, here is the explanation, as mentioned in the documentation, the scope of var
is greater than let
, so for example in the code when you declare in the% var i = 0
the reach is global , the variable is "raised" to the window object in the case of the browser. This behavior does not occur with let
, since let i = 0
is not "raised", but belongs to the for, its scope is only inside the for.
for (var i_var = 0; i_var < 10; i_var++) {
setTimeout(function() { console.log(i_var); }, 100 * i_var);
}
console.log("Valor de var: "+i_var);
for (let i_let = 0; i_let < 10 ; i_let++) {
setTimeout(function() { console.log(i_let); }, 100 * i_let);
}
console.log("Valor de let: "+i_let);
When executing that code, the error comes out that i_let is not defined, because it was not raised to window, once this is clarified now the answer does come:
At the end of the first for is shown the value of i_var
, that is 10 and each console.log()
of setTimeout
will refer to that value, because as you will have noticed, first print "Value of var: 10 ", then the error and then the others console.log()
are executed.
And in the second for it is different, because if the for and the variable i_let
no longer exists, what is happening? simply every console.log()
of the second for is referring to a different variable, each iteration represents a different value.
Therefore, even though the console.log()
is executed when the for and i_let
finished, it no longer exists, you can print a value, this is the variable that was created in the cycle and its value corresponds to the number of iteration.