JavaScript Hoisting 🚀

JavaScript Hoisting 🚀
Hoisting is JavaScript's behavior of moving variable and function declarations to the top of their scope before code execution.
1️⃣ What is Hoisting?
JavaScript automatically moves declarations to the top of their scope (global or function).
Only declarations are hoisted, not initializations.
2️⃣ Variable Hoisting 📦
✅ Hoisting with var (Hoisted but Undefined)
console.log(a); // ❌ Undefined (but no error)
var a = 10;
console.log(a); // ✅ 10
🔹 Explanation:
var a; is hoisted to the top, but its value (10) is NOT.
The first console.log(a); runs before assignment, so it prints undefined.
Equivalent Code (How JavaScript Interprets It)
var a;
console.log(a); // undefined
a = 10;
console.log(a); // 10
❌ Hoisting with let and const (Temporal Dead Zone - TDZ)
console.log(b); // ❌ ReferenceError: Cannot access 'b' before initialization
let b = 20;
console.log(b);
🔹 Explanation:
let and const are hoisted, but they stay in the "Temporal Dead Zone" (TDZ) until the line where they are declared.
Same issue with const
console.log(c); // ❌ ReferenceError
const c = 30;
🛑 Solution: Always declare let and const before using them.
3️⃣ Function Hoisting 🎭
✅ Hoisting with Function Declarations (Works Fine)
sayHello(); // ✅ Works, prints: "Hello!"
function sayHello() {
console.log("Hello!");
}
🔹 Explanation:
Function declarations are fully hoisted, so they can be called before they are defined.
❌ Hoisting with Function Expressions (Does NOT Work)
greet(); // ❌ TypeError: greet is not a function
var greet = function() {
console.log("Hi!");
};
🔹 Explanation:
greet is hoisted as undefined, so calling it before assignment causes an error.
Equivalent Code (How JavaScript Sees It)
var greet;
greet(); // ❌ TypeError
greet = function() {
console.log("Hi!");
};
4️⃣ Summary Table 📜
Feature var let const Function Declaration Function Expression
Hoisted? ✅ Yes ✅ Yes ✅ Yes ✅ Yes ✅ Yes
Value Hoisted? ❌ No (undefined) ❌ No (TDZ) ❌ No (TDZ) ✅ Yes ❌ No (undefined)
Usable Before Declaration? ✅ Yes (undefined) ❌ No (TDZ Error) ❌ No (TDZ Error) ✅ Yes ❌ No (Error)
5️⃣ Best Practices 🏆
✔️ Use let and const instead of var to avoid unexpected behavior.
✔️ Declare variables at the top of their scope.
✔️ Use function declarations when you need hoisting, or define function expressions before calling them.
6️⃣ Quick Quiz 🎯
What will be printed?
console.log(num);
var num = 42;
console.log(num);
❓ Answer:
✅ undefined
✅ 42
Date: 2025-03-29 00:00:00.000000