Temporal Dead Zone
Let's understand first Is hoisting applicable to both let
and const
?
When using
var
At the time of memory allocation,
var
is initialised withundefined
.When using
let
It appears that
let
is not being hoisted.But let me tell you variables declared with
let
andconst
are also hoisted. It's just that they're hoisted differently than var variables.Simply reading the error message reveals that it is aware that
a
has been declared but has not yet been initialized.If something is not declared, the error message will be different.
This shows that the variables declared with
let
are hoisted as well. The same holds true for theconst
keyword.
What exactly is the Temporal Dead Zone?
The Temporal Dead Zone is defined as the time between when the const
and let
variables were hoisted and when they were initialized with a value.
We know that the let
and const
are hoisted, but they are in the Temporal Dead Zone and thus cannot be accessed before their execution.
In this code example, the Temporal Dead Zone begins when the code execution enters the console. log(a)
and continues until the let a
is executed.