Temporal Dead Zone (TDZ) in JavaScript

neeraj1997dev

Neeraj Kumar

Posted on October 21, 2022

Temporal Dead Zone (TDZ) in JavaScript

The hoisting of variables declared with var is well known among JavaScript developers.

ES2015 version introduced two new keywords to declare variables and constants: let and const.

Unlike var, which can be accessed before it is declared, variables declared with let and constants declared using const cannot be accessed before their declaration.



console.log(name); // undefined
var name = "Neeraj";


Enter fullscreen mode Exit fullscreen mode


console.log(name); // Error
let name = "Neeraj";


Enter fullscreen mode Exit fullscreen mode

hoisting doesn’t apply to let and const; that is an incorrect assumption.
Example:



let name = "Neeraj Kumar";

function printName() {
  console.log(name);
  let name = 30;
}

printName(); // Error


Enter fullscreen mode Exit fullscreen mode

Temporal Dead Zone

So, if the let and const are also hoisted, why is it that they cannot be accessed before their declaration? The answer to this lies within the concept of the Temporal Dead Zone (TDZ).

Variables declared using let and the constants declared using const are hoisted but are in a TDZ. This prevents them from being accessed before their declaration has actually been executed during the step-by-step execution of the code.

Temporal Dead Zone is the period of time during which the let and const declarations cannot be accessed.

Temporal Dead Zone starts when the code execution enters the block which contains the let or const declaration and continues until the declaration has executed.

In our code example above, Temporal Dead Zone starts after the opening parenthesis of the printAge function and continues until after the declaration of the age variable.

Consider the following code example that illustrates an interesting point about the Temporal Dead Zone.



function print() {
  function log() {
    console.log(name);
  }

  const name = "Neeraj Kumar";
  log();
}

print(); // Neeraj Kumar


Enter fullscreen mode Exit fullscreen mode

name is accessed after the declaration of name variable because the console.log is inside another function that is called after the declaration of the age variable. By the time the age variable is accessed inside the log function, the age variable’s declaration has already been executed.

https://dev-to-uploads.s3.amazonaws.com/uploads/articles/i2s4i836pyo0hh0ve4a4.png

💖 💪 🙅 🚩
neeraj1997dev
Neeraj Kumar

Posted on October 21, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related