What Is Meant by Temporal Dead Zone in JavaScript?

Find out what temporal dead zone (TDZ) is in JavaScript

Temporal Dead Zone (TDZ) refers to the area in your code block, where a variable declared using let or const, is inaccessible (within its block scope) till it is evaluated.

The temporal dead zone starts at the time the variable is created within its containing block (which happens when the containing block is initialized), and it ends where the variable declaration is evaluated/processed:

{
    // TDZ starts at beginning of scope

    // ReferenceError: x is not defined
    console.log(x);

    // TDZ (for `x`) ends at variable declaration
    let x = 'foo';
}

As you can see in the code above, the variable "x" is inaccessible in the area/zone before its declaration is evaluated. The variable is only accessible and initialized once the let or const statement is evaluated:

{
    // TDZ starts at beginning of scope

    // TDZ (for `x`) ends at variable declaration
    let x = 'foo';

    // accessed outside TDZ
    console.log(x); // 'foo'
}

Compare this to the following, where a function is able to access a let variable before the position at which it is declared (without raising any error):

{
    // TDZ starts at beginning of scope
    const func = () => console.log(x);

    // TDZ (for `x`) ends at variable declaration
    let x = 'foo';

    // called outside TDZ
    func(); // 'foo'
}

The reason no exception is thrown in this instance is because the function itself is actually called outside the temporal dead zone for the variable "x" (even though its usage appears before its declaration). This means that, when accessing values of let or const variables, the order (or position) in which the code is written does not matter, but rather the order in which the code is executed is what matters.


Hope you found this post useful. It was published . Please show your love and support by sharing this post.