The specific section in the language specification can be found at 13.7.4
When a for
statement includes a let
or const
declaration, it results in the creation of a new scope.
A scope is created for each iteration if the for
statement contains a let
declaration.
If the body of the for
loop is enclosed in curly braces, then a scope is also created.
Here are some examples that demonstrate the creation of scopes:
// No additional scope
for(i = 0; i<3; i++) console.log(i);
// No additional scope
for(var i = 0; i<3; i++) console.log(i);
// Scope for 'i' and iteration scope
for(let i = 0; i<3; i++) console.log(i);
// Scope for 'i', iteration scope, and block scope
for(let i = 0; i<3; i++) {
console.log(i);
}
Why are iteration scopes necessary? They serve the purpose of closures:
for(let i = 0; i<3; i++) {
setTimeout(() => console.log(i), 10);
}
Output without iteration scope: 3,3,3. With iteration scope: 0,1,2