The Temporal Dead Zone (TDZ) is a concept in JavaScript that refers to the period between the creation of a variable and its declaration being reached in the code. During this time, accessing the variable will result in a ReferenceError. The TDZ exists for variables declared with ‘let’ and ‘const’.
When the JavaScript engine encounters a block scope (such as a function, if statement, or loop) containing a ‘let’ or ‘const’ declaration, it enters the TDZ for that variable. Within the TDZ, any attempt to access or reference the variable will throw a ReferenceError because the variable exists but is not yet initialized.
The TDZ ends when the variable’s declaration is reached in the code. After the declaration, the variable is accessible and can be assigned a value.
Example
function exampleFunction() {
console.log(x); // Throws ReferenceError: Cannot access 'x' before initialization
let x = 10;
console.log(x); // Output: 10
}
exampleFunction();
In this example, we have a function called exampleFunction(). Within this function, we try to access the variable x before its declaration, resulting in a ReferenceError being thrown. This is because the variable x is within the TDZ until its declaration is reached.
Once we move past the line let x = 10;, the TDZ for x ends, and we can successfully access and print the value of x, which is 10.
The TDZ ensures that variables are accessed only after they have been properly declared, promoting good coding practices and avoiding potential bugs caused by using variables before they are initialized.
It’s worth noting that the TDZ is not limited to function scope; it applies to block scope as well. The same concept would hold true within if statements, for loops, or any other block-level scope where variables are declared using let or const. Attempting to access such variables before their declaration within the same block would result in a ReferenceError due to the TDZ.