Temporal Dead Zone - jellyfish-tom/TIL GitHub Wiki
When a regular variable created using var is hoisted to the top of its scope, itโs initialized with the value undefined (as stated above), which is what allows us to be able to reference a normal variable before it has a value declared through assignment.
console.log(x); // undefined
var x = 10;
because of hoisting it actully is like this:
var x = undefined;
console.log(x); // undefined
x = 10;
Variables declared with let are hoisted, but crucially, they are not automatically initialised with the value undefined, which means that the following code produces an error:
console.log(x); // Uncaught ReferenceError: x is not defined
let x = 10;
This error is caused by the Temporal Dead Zone (TDZ). The TDZ exists from the moment the scope is initialized to the moment the variable is declared. To fix the ReferenceError, we need to declare the variable before trying to access it:
To fix
let x
console.log(x); // logs undefined
x = 10;
Another example:
IN ES6:
console.log(typeof tdzVariable === 'undefined'); // ReferenceError
const tdzVariable = 'I am initialized.';
IN ES5:
console.log(typeof undeclaredVariable === 'undefined'); // true