/
Write
Start a team blog
NEW ✨
Start a team blog, invite your team, and start publishing.
Temporal Dead Zone

Temporal Dead Zone

Ruchi Goswami's photo
Ruchi Goswami
·Jan 16, 2022·

2 min read

The Temporal Dead Zone (TDZ) is one of the important and advanced concepts of JavaScript, not explicitly defined in ECMA Script specifications. But programmers do understand this. The temporal dead zone is a behavior (in JavaScript) that occurs while declaring a variable with the let or constkeywords. This is not applicable to var keyword.

In JavaScript, variable declarations are hoisted to the top of the scope. The code in the example explains that:

console.log(message); 
var message = "Roses are red, violets are blue"; 

// undefined

The output is undefined because the variable declaration is hoisted to the top of the scope. So to the JavaScript interpreter, the code actually looks like:

var message;
console.log(message); 
message = "Roses are red, violets are blue";

The JavaScript interpreter works in two-steps:

  • compile time: run through all code looking for variable/function declarations
  • runtime: execute the code including assignments and function invocations

That's the reason message is defined on the first line but is not assigned. JavaScript automatically gives the value of undefined to the variables that are defined but not assigned with a value. Therefore, the result of line 2 will be undefined because the assignment occurs in line 3.

But if we use letor const keywords to declare the variable, the same code will throw an error:

console.log(message); 
let message = "Roses are red, violets are blue"; 

// ReferenceError: message is not defined
console.log(message); 
const message = "Roses are red, violets are blue"; 

// ReferenceError: message is not defined

So why we get the Reference error here? Because the variables are unreachable. They are in the scope, but are not declared. They are in a temporal dead zone.

The time span when that happens (Reference error), between the creation of a variable's binding and its declaration, is called the temporal dead zone.
-Dr. Alex Rauschmayer

Temporal dead zone exists to catch the programming errors. It is normally by accident that one tries to access variables before its declaration and therefore, one should be warned about it.

To conclude, let and const keywords get hoisted, but are not assigned undefined value. Best practice to make TDZ zero for variables in a program is to declare all the variables at the top of its scope.

Further Reading

Dr. Rauschmayer's post