JavaScript Hoisting
JS
What is Hoisting?
Hoisting is JavaScript’s default behavior of moving declarations to the top of the current scope (script or function) before the code runs.
This means:
- Variable declarations (var)
- Function declarations
are "hoisted" (raised) to the top of their scope.
- But only the declarations are hoisted, not the initializations.
Example with var
Behind the scenes, JavaScript interprets this like:
So the var x
declaration is hoisted, but = 5 is not.
That’s why it prints undefined first.
let
and const
are NOT hoisted in the same way
let and const are hoisted to the top of their block, but they are not initialized.
They stay in a "temporal dead zone" (TDZ) from the start of the block until the declaration line.
Same for const
.
Function Hoisting
Function declarations are hoisted with their bodies.
JavaScript moves the whole function definition to the top.
Function expressions are NOT hoisted
If you assign a function to a variable, only the variable is hoisted (not the function body).
JavaScript does this under the hood:
Quick summary table
Type | Hoisted? |
---|---|
var | ✅ Declaration hoisted, initialized as undefined |
let / const | ✅ Declaration hoisted, but in TDZ (not usable) |
Function declaration | ✅ Fully hoisted (definition + body) |
Function expression | ❌ Only variable is hoisted (not initialized) |
- Hoisting moves declarations to the top of their scope.
var
→ hoisted & initialized asundefined
.let
&const
→ hoisted but not initialized (TDZ).- Function declarations are hoisted completely.
- Function expressions are not hoisted (only the variable name is).