Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do for loops implicitly create a block?

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);
    }
  }
}
like image 566
Randomblue Avatar asked Jun 27 '13 20:06

Randomblue


1 Answers

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

  1. Let oldEnv be the running execution context’s LexicalEnvironment.
  2. Let loopEnv be the result of calling NewDeclarativeEnvironment passing oldEnv as the argument.
  3. ...

Keep in mind, though, that it's still subject to change.

like image 141
Jonathan Lonowski Avatar answered Oct 28 '22 02:10

Jonathan Lonowski