Take let variable out of temporal dead zone

# Oriol Bugzilla (8 years ago)

Consider this code:

<script>
let {foo} = null; // TypeError
</script>
<script>
// Here I want to assign some some value to foo
</script>

The first script attempts to let-declare foo via a destructuring assignment. However, null can't be destructured, so the assignment throws a TypeError. Some alternatives which would lead to the same problem are let foo = null.throw and let foo = (() => {throw;})().

Then the foo variable is declared but uninitialized, so if in the 2nd script I attempt to reference foo, it throws:

foo = 123; // ReferenceError: can't access lexical declaration `foo' before initialization

And let variables can't be redeclared:

let foo = 123; // SyntaxError: redeclaration of let foo

Is this behaviour intended? Is there any way to take foo out of the TDZ, so that I can assign values and read them?

Edit: I want to use foo, not workarounds like window.foo.

# Isiah Meadows (8 years ago)

Try window.foo. That's usually what's done within global IIFEs, which has similar scope restrictions.

# Jason Orendorff (8 years ago)

On Fri, Apr 15, 2016 at 12:52 PM, Oriol Bugzilla <oriol-bugzilla at hotmail.com> wrote:

Is this behaviour intended? Is there any way to take foo out of the TDZ, so that I can assign values and read them?

Yes, the behavior is intended. I know because I raised this issue here before the standard was finalized - search the archives.

And no, there's no standard way to fix it afterwards. You have to hit Refresh.

Firefox quietly changes the let-binding to undefined for you if you manage to get this when you're just typing in some code in the Firefox devtools. But it's a nonstandard hack.

# Awal Garg (8 years ago)

Not possible. Previous discussion: esdiscuss.org/topic/global-lexical-tier (the one Jason mentioned above).

Key take-away from the above, which is admittedly sad:

When it comes to aesthetics vs. implementability and usability, we have

to throw aesthetics under the bus. This is JavaScript, after all! :-P Ok, seriously, we did not actually make anything prettier. The top level is hopeless. All we did was leave a couple of hazards for implementors and users in ES6.

:(