Temporal Dead Zone (TDZ) is a term used in JavaScript to describe the behaviour of variables declared using the let
and const
keywords. In JavaScript, variables declared using these keywords are hoisted to the top of their respective scopes, but unlike var
variables, they cannot be accessed until they are assigned a value.
The TDZ is the period between the start of scope and the point at which a variable declared with let
or const
is initialized. During this time, any attempt to access the variable will result in a ReferenceError
.
For example:
javascriptCopy codeconsole.log(a); // Throws ReferenceError
let a = 10;
In this code, the variable a
is declared using let
, but its value is not assigned until the second line. As a result, the first line will throw a ReferenceError
because the variable is still in the TDZ.
The TDZ serves as a way to enforce the proper use of let
and const
variables in JavaScript, as it prevents accidental use of uninitialized variables. It also encourages developers to declare their variables at the top of their respective scopes, rather than relying on hoisting.