Redefining a let variable inside a for loop scope doesn't work?

Allen Wirfs-Brock allen at wirfs-brock.com
Fri Jul 15 14:18:41 UTC 2016


This is by design.  ECMAScript block scoped declarations generally conform to the principle that within a single block or statement a name may have only a single binding. For example, 

```js
let x=0;
{
  let x = x+1;  //access to uninitialized variable error because both the RHS and LHS refer to the inner x
                     //which has not yet been initialized when the RHS is evaluated
}

```

The same principle also applies to 
```js
let n = {a:[]};
for (let n of n.a) ;
```

although the actual scoping of the `for` statement is more complex. Basically, such `for` statements consider all names bound by the `let` part of of the `for` header to be undefined while the `of` expression is being evaluated. 

This is done to avoid any confusion about which `n` the expression references. Such confusion is avoid by all references to the `let` bound names from the RHS errors.

Allen





More information about the es-discuss mailing list