Hoisting Explained - var vs let vs const
Hoisting is a JavaScript behavior where variable and function declarations are moved to the top of their scope during the memory creation phase.
In simple words:
JavaScript processes declarations before executing code.
How JavaScript Executes Code
Execution happens in two phases:
- Memory Creation Phase
- Variables and functions are stored in memory
- Execution Phase
- Code runs line by line
Function Hoisting (Fully Hoisted)
Example:
Output:
Why?
Function declarations are completely hoisted, so you can call them before they are defined.
var Hoisting (Partial Hoisting)
Example:
Output:
Explanation:
Only the declaration is hoisted, not the assignment.
var is initialized with undefined.
let and const Hoisting (Temporal Dead Zone)
Example:
Output:
Explanation:
let and const are hoisted, but they are not initialized.
They remain in the Temporal Dead Zone (TDZ) until execution reaches their declaration.
TDZ is the time between variable creation and initialization.
Function Expression Hoisting
Example:
Output:
Explanation:
This is treated like a variable:
So:
- Variable is hoisted
- Function is not assigned yet
Function Expression with let
Output:
Explanation:
Because let is in the Temporal Dead Zone, it cannot be accessed before initialization.