The Temporal Dead Zone (TDZ) in JavaScript refers to the period between when a variable is scoped (declared) and when it is initialized with a value. During this time, attempting to access the variable will result in a ReferenceError.
The TDZ applies to variables declared with let
and const
. Unlike var
, which is hoisted and initialized with undefined
, let
and const
are hoisted but not initialized until their declaration is executed.
let
and const
declarations are hoisted to the top of their scope but not initialized.
The TDZ
for a
starts when the block is entered and ends when the let a = 5;
statement is executed.
const
const
behaves the same way but must be initialized at the time of declaration:
let
and const
and their actual initialization.var
does not have a TDZ because it is initialized with undefined
when hoisted.Would you like a real-world example where TDZ might cause bugs? 🚀