What is the Temporal Dead Zone in JavaScript?

In JavaScript, all declarations that mean var, let, const, function, function*, class are hoisted.

Temporal Dead Zone:

let and const are hoisted but there is a time difference between entering scope and being declared where they cannot be accessed. This period is called the temporal dead zone (TDZ).

Following is an example of hoisting of let variable:

console.log(carBrand);    // undefined
console.log(techCompany); // Uncaught ReferenceError: Cannot access 'techCompany' before initialization

var carBrand = ['BMW', 'Audi'];
let techCompany = ['Google', 'Apple'];

Now consider the following example:


let name = 'Joe';
(function() {
    // start TDZ for x
    console.log(name);
    let name = 'Carol'; // TDZ for variable name
}());

Accessing name variable in the inner scope still causes a ReferenceError. If let were not hoisted, name variable would log outer value.

The Temporal Dead Zone is a good thing because it helps to highlight bugs—accessing a value before it has been declared.