A temporal dead zone in JavaScript is the area of a block where a variable is inaccessible until the computer completely initializes it with a value.
-
Block is a pair of braces (
{...}
) used to group multiple statements. - Initialization occurs when you assign an initial value to a variable.
Temporal Dead Zone is the period of time during which the let
and const
declarations cannot be accessed.
Example:
Before Stepping deep into this concept I would recommend you to know about Hoisting in JavaScript.
let and const have two broad differences from var:
- They are block-scoped.
- Accessing a
var
before it is declared has the result undefined; accessing alet or const
before it is declared throwsReferenceError:
Where exactly does the TDZ begin and end?
The above example shows that let
and const
variables are not accessible before they are initialized with some value, and the phase between the starting of the execution of the block in which the let
or const
variable is declared till that variable is being initialized is called Temporal Dead Zone for the variable.
In other words, a block’s temporal dead zone starts at the beginning of the block’s local scope. It ends when the computer fully initializes your variable with a value.
And during this zone JavaScript will always through a reference error if anyone tries to access those variables.
Example:
Above Code Result: JavaScript will return a ReferenceError
because we used the console.log() code to access age
before its complete initialization. In other words, we invoked age
within the temporal dead zone.
Start and End of TDZ: In the above example, Temporal Dead Zone starts after the opening parenthesis of the printAge function and continues until after the declaration of the age variable.
The Temporal Dead Zone is not about where, but about when the let
variable or const
constant is accessed. Temporal Dead Zone relates to time, not the space above the declaration of let or const.
In above example before calling to log() the age constant is declared and initialized so it is accessible in log function.
Conclusion:
The most efficient way to overcome the errors of the temporal dead zone is to initialize the variables at the top of the scope so that when our code starts running it completes the initializing part at first and then uses those variables otherwise you can run into a lot of unexpected errors in JavaScript code.
Exploring new concepts in JavaScript and sharing with others is my passion and it gives me pleasure to help and inspire people. If you have any questions, feel free to reach out!
Connect with me on Twitter, Linkedin, GitHub and Dev Community!
0 Comments