Hoisting and Temporal Dead Zone
JavaScript Hoisting
JavaScript goes through the code file collects references and stores those references in memory and executes code line-by-line.
The memory preparation phase is a hoisting, Take functions and store their reference, take let
and const
set uninitialized until get values and var set a undefined.
function
: functionReferencelet
,const
: uninitializedvar
: undefined
Case 1: Access fn before declaration.
No issue occurs when function call before declaration.
Case 2: Access var before declaration.
When you use var
before their declaration error occurs as undefined
.
Error:
No Error:
Case 3: Access let
/const
before declaration.
When you use let
or const
before their actual declaration, an error occurs as Reference error
.
Error:
No Error:
Temporal Dead Zone
Zone before the actual declaration, Zone between variable use and its declaration is called TDZ.
Subscribe to my newsletter
Read articles from Saurabh Tajane directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by