Temporal Dead Zone (TDZ) in JavaScript

Shameera Carrim
2 min readOct 10, 2022

--

In JavaScript, the variables and functions are hoisted and are able to access in top of their scope.

For example,

console.log(studentName);
printAge(12);
var studentName = "Windy";
function printAge(age){
console.log("Age is: ",age);
}

There are two keywords that was introduced by JavaScript ES2015 version to create variables and constants called let and const . Lets see how they behave when attempted access before initialization.

var

console.log(studentName) //undefinedvar studentName = "Peter"

const

console.log(studentAge) // Errorconst studentAge = 12

let

console.log(studentClass) // Errorlet studentClass = 7

Let’s see if they are hoisted.

At line number 1, even before code has started to execute, JavaScript has allocated memory to studentAge, studentIndex and studentClass and available in scope. Variable declared with var keyword attached to global space and the variable declared with let and const is attached to script space.

If const and let are also hoisted, why are the variables and constants unable to access prior to the initialization ❓

That is because of temporal dead zone (TDZ).

But what is meant by TDZ ❓ 😕

It is the time from let or const variable is hoisted and until it is initialized with some value.

If we try to access a const or let variable TDZ phase, output will be an referenceError.

Attempting to access let variable during TDZ
Attempting to access const variable during TDZ

A referenceError will be fired because variable cannot be accessed during TDZ.

The best way to avoid above errors and avoid chances of accessing TDZ, is to declare variables within the top of the specific scope.

Want to know more about errors? (Read about errors in js)

--

--