Middle+
What is the Temporal Dead Zone (TDZ)? Why does it appear and how to deal with it?
sobes.tech AI
Answer from AI
The Temporal Dead Zone (TDZ) is the period of time between the start of a block of code (for example, a {} block) and the moment a variable is declared using let or const, during which the variable cannot be accessed. If you try to use the variable before its declaration, a ReferenceError will be thrown.
TDZ occurs because variables declared with let and const are not hoisted in the same way as var. They exist in the scope but are not initialized until the line of declaration.
To avoid errors related to TDZ, you should:
- Declare variables at the beginning of the block or before use.
- Do not access variables before their declaration.
Example of TDZ:
{
console.log(a); // ReferenceError: Cannot access 'a' before initialization
let a = 10;
}