What is Temporal Dead Zone (TDZ) In Javascript

What is Temporal Dead Zone (TDZ) In Javascript

ยท

2 min read

My recent deep dive into Javascript revealed a key term called Dead Zone in Javascript, which is an advanced topic.

Definition

In Javascript, a temporal deadzone (TDZ) is an area of the block in a lexical environment where "let and const" declarations are not accessible, implying that our "let and const" variables are hoisted but not just accessible.

We'll look at some Javascript deadzone examples as well as how our let and const are hoisted but not accessible.


Let & Const Declarations are Hoisted

Just like Var, Let and Const also get hoisted. In the hoisting phase, variables declared with Var are moved to the top of the script and assigned an undefined initialization value.

console.log({name}); // undefined
var name = "Eeskay01";

Let and Const variable declarations are hoisted also but without an initialization default value because Let and Const Variable declarations are in a Temporal Deadzone before initialization.

console.log({language}); // ReferenceError: Cannot access 'language' before initialization
let language = "English";

Temporal Deadzone (TDZ) Examples

Example 1

function callName() {
  // Temporal deadzone starts here
  console.log({ name }); 

  let name = "Abidemi"; // Temporal deadzone ends here
};

callName();

// Uncaught ReferenceError: Cannot access 'name' before initialization at callName

In the above code, the temporal deadzone starts from the open parenthesis and stops when the name variable is been declared, running the code returns a reference error.

Example 2

function greetUser() {
  function username() {
    console.log({name});
  }

  let name = "Abidemi";

  username();
}

greetUser()

// { name: 'Abidemi' }

Because the name variable was declared before the username function call, the code above returns "Abidemi" as expected. Changing the position of the name variable declaration line after the username function call causes a temporal deadzone.

Check the code below.

function greetUser() {
    // TDZ starts
  function username() {
    console.log({name});
  }

  username();

  let name = "Abidemi"; // TDZ ends
}

greetUser()

// Uncaught ReferenceError: Cannot access 'name' before initialization

Conclusion

Let and Const are hoisted in the same way as Var, but with a different default Initialization value. Let and Const variables are not accessible in the Temporal Dead Zone.

I hope you find this helpful ๐Ÿ˜Š.

More Resources

ย