JavaScript — Hoisting
The illusion
Using a function before its definition works:
sayHi(); // "Hi!" — runs fine!
function sayHi() {
console.log("Hi!");
}
JavaScript's two-pass reading: it scans all declarations first (hoisting), then executes. Declarations are registered early; assignments are not.
What actually hoists
| Declaration | Behavior before its line |
|---|---|
function | fully usable ✓ |
var | exists as undefined |
let / const | exist but unusable (TDZ) |
| class | unusable like let |
console.log(a); // undefined 😕
var a = 5;
console.log(b); // ReferenceError!
let b = 6;
Temporal dead zone (TDZ)
Between block start and the let/const line, the variable exists but can't be touched:
{
// TDZ for x starts here
// console.log(x) would throw
const x = 1; // TDZ ends
}
This is a safety feature: bugs surface loudly instead of silently being undefined.
Only declarations, never initializers
var name = "Ada";
// becomes effectively:
// var name; ← hoisted
// name = "Ada"; ← stays put, runs in order
console.log(name); // undefined if read before assignment line
Function expressions vs declarations
run(); // TypeError: run is not a function (var holds undefined)
var run = () => "go";
jump(); // works — real declaration
function jump() { }
The arrow stored in a variable follows variable rules, not function-declaration rules. This trips people constantly when reordering code.
Practical takeaways
- Declare at top of scope — hoisting knowledge becomes irrelevant
- Prefer
let/constso accidental early reads throw instead of whisperundefined - Function declarations may sit below callers safely (common in module files)
Mini Practice
- Call-before-define both styles; compare error messages
- Log a
varbefore its line; log alet— contrast outcomes - Reorder an arrow-function callback to prove the TypeError case
- Sketch on paper what two-pass execution means for a 5-line script
Next: strict mode →
Related Topics
Frequently Asked Questions about Hoisting
What is Hoisting in JavaScript?
Hoisting is a fundamental concept in JavaScript. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn Hoisting?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Hoisting.
Why is Hoisting important in JavaScript?
Hoisting is essential for JavaScript development. Understanding this concept will help you write better code and solve real-world problems more effectively.