Introduction
A temporal dead zone (TDZ) is the block where a variable is inaccessible until the moment the computer initializes it with a value.
- A block can be defined as a pair of braces ({...}) used to accumulate multiple statements.
- Initialization occurs when one assigns an initial value to a variable.
Suppose a user attempts to access a variable before its complete initialization. In such a scenario, JavaScript will subject a ReferenceError.
Scope of a Temporal Dead Zone
We will explain the scope of a Temporal Dead Zone with the following example.
{
// bestPlace’s TDZ starts here (at the beginning of this block’s local scope)
// bestPlace’s TDZ continues here
// bestPlace’s TDZ continues here
// bestPlace’s TDZ continues here
console.log(bestplace); // returns ReferenceError because bestplace’s TDZ continues here
// bestPlace’s TDZ continues here
// bestPlace’s TDZ continues here
let bestPlace = "Delhi"; // bestPlace’s TDZ ends here
// bestPlace’s TDZ does not exist here
// bestPlace’s TDZ does not exist here
// bestPlace’s TDZ does not exist here
}
In the snippet described above, the block’s TDZ starts from the opening curly brace ({) and ends once the computer initializes bestPlace with the string value "Delhi".
When users run the snippet, they will see that the console.log() statement will return a ReferenceError.
Complete Initialisation of bestPlace is described below.
{
// TDZ starts here (at the beginning of this block’s local scope)
// bestPlace’s TDZ continues here
// bestPlace’s TDZ continues here
// bestPlace’s TDZ continues here
// bestPlace’s TDZ continues here
// bestPlace’s TDZ continues here
// bestPlace’s TDZ continues here
let bestPlace= "Delhi"; // bestPlace’s TDZ ends here
console.log(bestPlace); // returns "Delhi" because bestPlace’s TDZ does not exist here
// bestPlace’s TDZ does not exist here
// bestPlace’s TDZ does not exist here
}