DEV Community

Muhibullah
Muhibullah

Posted on

(TDZ) Temporal Dead Zone in JavaScript – Simple Explained

What is the temporal dead zone in JavaScript?

Temporal Dead Zone(TDZ) is the time when the variable exists but is still uninitialized and cannot be accessed [so if we try to access it at this time, we will get an error] It ends when the code declaration. it is behavior specific to let and const variables.

{
  // userName TDZ starts here (local scope block)
  // userName TDZ running...
  // userName TDZ running...

  console.log(userName);
 /* ReferenceError: can't access lexical declaration 'userName' before initialization, because userName TDZ running here.*/

  // userName TDZ running...
  // userName TDZ running...

  let userName = "muhibullah"; // userName TDZ ends

  // userName TDZ not exist here
  // userName TDZ not exist here
}
Enter fullscreen mode Exit fullscreen mode

How does "var" TDZ different from "let" and "const" variables?

var is function scoped and can be reassigned multiple times, let is block scoped and can be redeclared and reassigned, and const is block scoped and cannot be reassigned after initialization. TDZ is behavior specific to let and const variables that prevent their use before they have been properly initialized.

{
  // userName TDZ start and end here.

  console.log(userName); // log: "undefined" because userName TDZ not exist.

  var userName = "muhibullah"; // userName TDZ not exist

  console.log(userName); // log: "muhibullah" because userName TDZ not exist

  // userName TDZ not exist here
  // userName TDZ not exist here
}
Enter fullscreen mode Exit fullscreen mode

In summary, TDZ (Temporal Dead Zone) is a behavior specific to let and const variables in JavaScript that prevents their use before they have been properly initialized. When a let or const variable is declared, it is in the TDZ until it is initialized, and trying to access it before initialization will result in a ReferenceError. This behavior is in place to prevent the use of variables before they have been properly defined.

declaring and initialization: declaration is the process of creating a new variable with a specific name, while initialization is the process of assigning an initial value to a variable. declaration and initialization can occur in the same statement.

Top comments (0)