Temporal Dead Zone Javascript
- The time between the declaration & initialization of
let&constvariables. - The term to describe the state where variables are in the scope but they are not yet declared.
- During this time, the variable is in the TDZ and cannot be accessed, leading to a
ReferenceErrorif you try to use it before its declaration is encountered. - The TDZ starts at the beginning of the block scope & ends when the variable is declared and initialized.
Example
console.log(a); // ReferenceError: Cannot access 'a' before initialization
let a = 5;
function example() {
console.log(b); // ReferenceError: Cannot access 'b' before initialization
let b = 10;
}
example();
- The variables
a&bare in the Temporal Dead Zone from the start of the block until their initialization (i.e., whenlet a&let bare encountered).