ES6 - The temporal dead zone


// ES6 - Temporal Dead Zone:

A variable declared with either let or const cannot be accessed until after 
the declaration.  Attempting to do so results in a reference error, even when 
using normally safe operations such as with the typeof operator:

if (condition) {
  console.log(typeof x); // throws an error
  let x = "blue";

In the above code, the variable x is defined and initialized using let, but that 
statement is never executed because the previous line throws an error.  The 
issue is that the value exists in what the JavaScript community called the 
temporal dead zone (TDZ).  The TDZ is never named explicitly in the ECMAScript 
specification, but the term is often used to describe why let and const bindings 
are not accessible before their declaration.

However, you can use typeof on a variable outside the block where that variable 
is declared, although it may not produce the results that you may expect.  

console.log(typeof x); // "undefined"
if (condition) {
  let x = "blue";

The above code works fine with ES6.  It also work fine prior to ES6, but this is 
probably because prior to ES6, we were using the var keyword, which is hoisted 
to the top.
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License