We have discussed before that let and const
both are hoisted too. But if you try to access a let or const data structure before it's initialized, this is what you get:
console.log(a);
let a=10;
This error is encountered because a
is in temporal dead zone
Temporal Dead Zone
When we declare and initialize data using let
and const
keywords, unlike var
, they are stored in a separate memory space which is not a part of the global space.
So, even though in the first phase of memory allocation, they are hoisted and given value undefined until initialized, they cannot be accessed.
This space between first line of code to execution of code where they are initialized is called the temporal dead zone.
let can be declared in one line and initialized later, but const keyword when used, must be initialized in the same line or throws an error. It is more strict than let.
⭐ var vs let vs const by freecodecamp
⭐ js introduction by interviewbit
Top comments (2)
To be precise the 'temporal dead zone' is the time between accessing a variable and till its 'SCOPE' is created. Therefore try accessing them in a block or a function before initializing, see the magic.
I took up blocks and block scope in here:
dev.to/aishanipach/block-scope-2g3n
Do check it out and let me know if there is anything that can be improved, thank youu!