I thought I understood the "closure" behaviour of Javascript, and to prevent the most complex problem of this I usually use "let" instead of "var" in all my code. But it seems it is not enough in this case.
I defined a variable in a for
loop (called i
here for more conveniance). In my loop, I call a function, which has not any parameters, defined somewhere outside the loop, which use this very variable. But it seems that it cannot reach the value of i
, even if it is present in the loop scope.
I know that if I defined the variable i
outside the loop, or if I remove let
in the for
line, it would solve my problem. The question is : why does not my function know the value of i
?
function printiValue()
{
alert(i);
}
let table = [1,2,3];
for (let i of table)
{
printiValue();
}