What\'s exactly the action scope of let
in a for-loop in JavaScript?
Variables declared with let
are not visible (accessible) outside their scope, which explains the error raised by the console.log
that is outside the for loop).
It also explains why the loop runs three times and prints 4
, the explanation is that the i
inside the for loop block (the one declared as let i = 4;
) is different than the i
in the loop header due to the invisibility that comes with the let
keyword, i.e., the i
in let i = 4;
which is inside the for loop block is not visible in the for (let i = 0; ...)
, they're different, and so the one inside the block is not affecting the one outside (in the header).