The Temporal Dead Zone (TDZ) in JavaScript refers to the period between the creation of a variable in the scope and its initialization. During this period, the variable is in an uninitialized state and cannot be accessed. Attempting to access it will result in a ReferenceError.
Key Points:
TDZ occurs with let and const: Unlike var, variables declared with let and const are not hoisted to the top of their scope in an accessible way.
Access before initialization throws ReferenceError: The variable exists in memory but is not initialized until the declaration is executed.
TDZ ends when the variable is initialized: Once the declaration line is executed, the variable becomes accessible.
Code Example 1: Accessing a Variable in the TDZ
console.log(x); // ReferenceError: Cannot access 'x' before initialization
let x = 10;
console.log(x); // 10
Explanation:
- The variable x exists in memory due to let declaration but is not initialized.
- Attempting to access it before initialization throws a ReferenceError.
Code Example 2: TDZ with const
console.log(y); // ReferenceError: Cannot access 'y' before initialization
const y = 20;
console.log(y); // 20
Explanation:
- const behaves the same as let during the TDZ. Accessing y before its initialization results in a ReferenceError.
Code Example 3: TDZ in Block Scope
{
console.log(a); // ReferenceError: Cannot access 'a' before initialization
let a = 5;
console.log(a); // 5
}
Explanation:
- The variable a is in the TDZ until the let a = 5 line is executed within the block.
Code Example 4: No TDZ with var
console.log(b); // undefined
var b = 15;
console.log(b); // 15
Explanation:
- Variables declared with var are hoisted and initialized with undefined. There is no TDZ for var.
Code Example 5: Function and TDZ
function example() {
console.log(c); // ReferenceError: Cannot access 'c' before initialization
let c = 30;
}
example();
Explanation:
- c is in the TDZ until the let c = 30 line is executed.
Code Example 6: TDZ with Default Parameter
function test(x = y, y = 10) {
console.log(x, y);
}
test(); // ReferenceError: Cannot access 'y' before initialization
Explanation:
- Default parameters are evaluated left-to-right. Here, x tries to access y before it is initialized, causing a ReferenceError.
How to Avoid Issues with TDZ
- Declare variables at the top of their scope.
- Initialize variables immediately after declaring them if possible.
- Understand the block scope behavior of let and const.
By being mindful of the TDZ, you can write more predictable and bug-free JavaScript code.
Top comments (0)