What\'s exactly the action scope of let
in a for-loop in JavaScript?
ECMAScript 2015 has a particular clause1 to cover what a for
loop does when it has a variable defined with let
in the control structure.
My reading of it is that it is specifically designed to provide a separate environment record for the variable within the loop body so that its value in a loop iteration will be seen by nested functions used as call backs - and in the process obviating the need to capture the value of a loop variable in a closure.
Essentially
for( let i=0; condition; ++i) {
...
}
i
set to zero;i
and stores the result in the new environment record for the next loop iteration (if it executes).Comparing the behavior with block scoping of variables within curly braces is misleading - the lexical scoping of the variable to the for
loop body does not require block braces to be used:
for( let i = 0; i < 2; ++i) continue;
console.log( i);
So the body scoping of the let
variable is a language design "special".
1Refer to CertainPerformance's answer for technical details of the specification.