I am playing with let
in Node.JS (requires the flags --harmony
and --use-strict
). As I understand, the let
statement allows for block scoped declarations. Consider the following:
let a;
for(let i = 0; i < 3; i += 1) {
console.log(i);
}
How many block scopes are involved? In which block scope does i
live in? Am I correct in thinking that for this example to work, there are three block scopes involved, with one scope implicitly created by the for
loop, as follows?
{ // block #1
let a;
{ // block #2 (contains `i`)
let i;
for(i = 0; i < 3; i += 1) { // block #3
console.log(i);
}
}
}
Based on the most recent (May 14, 2013) draft of ES6: yes.
You can find the following under section 12.6.3, which states that an additional Environment (scope) is created when a for
statement includes a LexicalDeclaration (let
or const
):
IterationStatement : for ( LexicalDeclarationNoIn ; Expressionopt ; Expressionopt ) Statement
- Let oldEnv be the running execution context’s LexicalEnvironment.
- Let loopEnv be the result of calling NewDeclarativeEnvironment passing oldEnv as the argument.
- ...
Keep in mind, though, that it's still subject to change.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With