JavaScript Roadmap — Day 30: Hoisting — JavaScript's Declaration Magic

 

 

📊 Your Progress Day 30 of 180 (17%)
🚀 Beginner Phase (Days 1-30) — FINISHING TODAY! 🎉 ⚡ Intermediate (31-90) 🏆 Advanced (91-180+)
📘 EASY Beginner Friendly · Last Day of Beginner Phase 🎓
JavaScript · Day 30 of 180 · Beginner Phase — 🎉 LAST DAY OF BEGINNER PHASE! 🎉

Hoisting — JavaScript's Declaration Magic

Hoisting is JavaScript's behavior of moving declarations to the top of their scope. Understanding it explains why some code works and some doesn't — and separates beginners from pros.

Day 30 / 180
Beginner Phase Complete! 🎓
🕐13 min read
💻6 code examples
🎯3 practice tasks
📝5 quiz questions

1. The Problem — Confusing Behavior

Have you ever wondered why this code works? It seems like you're using a variable before declaring it!

The Mystery
// How does this work? 'myVar' is used BEFORE declaration!
console.log(myVar);  // undefined (not an error!)
var myVar = 5;
console.log(myVar);  // 5

// But this DOES cause an error:
console.log(myLet);  // ❌ ReferenceError!
let myLet = 5;

// Why the difference? Hoisting is the answer!

💡 The insight: Hoisting is JavaScript's behavior of moving declarations to the top of their scope during compilation. But there's a catch — only the declaration is hoisted, not the initialization.

2. Hoisting Explained — What Actually Happens

When JavaScript executes your code, it actually goes through two phases: compilation (where it finds all declarations) and execution (where it runs your code). During compilation, JavaScript "hoists" (lifts) all variable and function declarations to the top of their scope.

Think of hoisting like moving all your declarations to the top of a page before reading the rest. The declarations are there, but their values aren't assigned yet. That's why you get undefined instead of an error.

Hoisting Visualization
// What you WRITE:
console.log(name);
var name = "Waheed";

// How JavaScript INTERPRETS it (after hoisting):
var name;                    // Declaration hoisted to top
console.log(name);              // undefined
name = "Waheed";               // Initialization stays in place

// Only the DECLARATION is hoisted, not the VALUE!
📝 QUIZ Test Your Understanding

Question 1: What is hoisting in JavaScript?

3. var vs let/const — The Temporal Dead Zone

Variables declared with let and const are also hoisted, but they are in a Temporal Dead Zone (TDZ) from the start of the block until the declaration is encountered. Accessing them before declaration causes a ReferenceError — which is actually better than getting undefined because it helps you catch bugs!

This is one reason modern JavaScript prefers let and const over var. The TDZ prevents you from using variables before they're properly initialized, making your code more predictable.

Temporal Dead Zone (TDZ)
// var — hoisted with undefined (dangerous!)
console.log(varVar);  // undefined (no error, but confusing)
var varVar = 5;

// let — hoisted but in TDZ (ReferenceError — better!)
console.log(letVar);  // ❌ ReferenceError: Cannot access before initialization
let letVar = 5;

// const — same as let, but must be initialized
const constVar;  // ❌ SyntaxError: Missing initializer

// TDZ visualized:
// ┌─────────────────────────────────────┐
// │  TEMPORAL DEAD ZONE (cannot access)  │
// │  console.log(x); ← ReferenceError!    │
// │  ───────────────────────────────────  │
// │  let x = 5; ← TDZ ends here           │
// └─────────────────────────────────────┘
📝 QUIZ Test Your Understanding

Question 2: What happens when you try to access a let variable before its declaration?

4. Function Hoisting — Different Rules

Function declarations are fully hoisted — you can call them before they appear in your code. Function expressions (even arrow functions) follow variable hoisting rules (only the variable is hoisted, not the function body).

Function Hoisting
// ✅ Function DECLARATION — fully hoisted (works!)
sayHello();  // "Hello!"
function sayHello() {
  console.log("Hello!");
}

// ❌ Function EXPRESSION — not hoisted (error!)
sayGoodbye();  // ❌ TypeError: sayGoodbye is not a function
const sayGoodbye = function() {
  console.log("Goodbye!");
};

// ❌ Arrow function — same as expression (error!)
sayHi();  // ❌ ReferenceError
const sayHi = () => console.log("Hi!");

5. Common Mistakes to Avoid

Mistakes & Fixes
// ❌ MISTAKE: Assuming let/const are not hoisted
console.log(myLet);  // ReferenceError — they ARE hoisted, just in TDZ!
let myLet = 5;

// ❌ MISTAKE: Relying on var hoisting (creates confusion)
console.log(x);  // undefined (not an error — but misleading!)
var x = 10;

// ✅ FIX: Always declare variables at the top
var x;  // Declare at top
console.log(x);  // undefined (expected)
x = 10;

// ✅ BETTER: Use let/const and declare before use
let y = 10;  // Declare AND initialize before use
console.log(y);  // 10

6. Best Practices — Professional Advice

🎯 Declare Variables at the Top
Even with hoisting, declare all your variables at the top of their scope. This makes your code more readable and predictable.
🔒 Never Rely on Hoisting
Just because you can use a variable before declaring it doesn't mean you should. Always declare before use for clarity.
📦 Use let/const, Avoid var
let and const have better scoping rules and the TDZ helps catch bugs. Modern JavaScript code rarely uses var.
📝 Prefer Function Declarations for Top-Level Functions
Function declarations are hoisted, making them available anywhere in their scope. This is useful for utility functions.

7. Try It Yourself — Hoisting Visualizer

See hoisting in action! Click the buttons to test different variable types.

✏️ Hoisting Visualizer
HTML
JAVASCRIPT
LIVE PREVIEW
💡 Click buttons to see how var, let, and functions are hoisted differently!

8. Practice Tasks

Task 1 — Easy: Predict the Output

What will be the output of this code?
console.log(a); var a = 10; console.log(a);
Write down your answer, then run it to check.

Task 2 — Medium: Fix the TDZ Error

This code causes an error. Fix it without removing the console.log:
console.log(myName); let myName = "Waheed";

Task 3 — Hard: Create a Hoisting Demonstration

Write three examples showing: (a) var hoisting, (b) let TDZ error, (c) function declaration hoisting. Explain each in comments.

🔥 Challenge of the Day

What will be the output of this tricky code? Write your answer before running it!

var x = 5;
function test() {
  console.log(x);
  var x = 10;
  console.log(x);
}
test();
🔍 View Solution
Output: undefined, 10
Explanation: Inside the function, the local 'var x' is hoisted to the top.
So the first console.log sees the local x (declared but undefined),
not the global x=5. Then x=10 assigns the value, so second log shows 10.
🎯 Key Takeaways
  • Hoisting moves declarations to the top of their scope during compilation
  • var is hoisted and initialized with undefined
  • let/const are hoisted but are in the Temporal Dead Zone (TDZ) — accessing them causes ReferenceError
  • Function declarations are fully hoisted (can be called anywhere)
  • Function expressions and arrow functions follow variable hoisting rules
  • Always declare variables at the top of their scope for clarity
💼 Common Interview Questions

Q: What is hoisting in JavaScript?

💡 A: Hoisting is JavaScript's behavior of moving variable and function declarations to the top of their scope during compilation.

Q: What's the difference between hoisting with var and let?

💡 A: var is hoisted and initialized with undefined. let is hoisted but not initialized — it's in the Temporal Dead Zone (TDZ) until the declaration is reached.

Q: Can you use a function before declaring it?

💡 A: Yes, if it's a function declaration. No, if it's a function expression or arrow function.

📖 Download Hoisting Cheat Sheet
Quick reference for var, let, const, and function hoisting
🎉🏆🎓
Congratulations! 🎉
You've completed the Beginner Phase (Days 1-30)!
30 lessons, 30 days of hard work. You're now ready for Intermediate Phase!
Enjoying this roadmap?
Follow Muhammad Waheed Asghar for daily JavaScript tips and updates!

Popular Posts