JavaScript Hoisting Explained: Var, Let, Const, and Functions

🚀 JavaScript Hoisting 💥 JavaScript Hoisting Explained: Why Your Code Breaks Before It Runs 👉 Hoisting is JavaScript's behavior of moving declarations to top of their scope during execution. 🔹 1. What Gets Hoisted? - var: Hoisted, initialized as undefined - let: Hoisted, not initialized (TDZ) - const: Hoisted, not initialized (TDZ) - function: Fully hoisted 🔹 2. Variable Hoisting (var) console.log(x); var x = 5; 👉 Output: undefined 👉 Behind the scenes: var x; console.log(x); // undefined x = 5; 🔹 3. let & const Hoisting (TDZ) console.log(a); let a = 10; 👉 Output: ReferenceError 👉 Why? Because of Temporal Dead Zone (TDZ) 👉 Variable exists but cannot be accessed before declaration 🔹 4. Function Hoisting ✅ Function Declaration (Fully Hoisted) greet(); function greet(){  console.log("Hello"); } 👉 Works perfectly ❌ Function Expression (Not Fully Hoisted) greet(); var greet = function(){  console.log("Hello"); } 👉 Output: TypeError: greet is not a function 🔹 5. Temporal Dead Zone (TDZ) 👉 Time between: Variable hoisted Variable declared During this time → ❌ cannot access variable {  console.log(x); // ❌ Error  let x = 5; } 🔹 6. Common Mistakes ❌ Using variables before declaration ❌ Confusing var with let ❌ Assuming all functions behave the same ⭐ Most Important Points ✅ var → hoisted with undefined ✅ let/const → hoisted but in TDZ ✅ Function declarations → fully hoisted ✅ Function expressions → not fully hoisted 🎯 Quick Summary - JavaScript moves declarations up, not values - var → usable before declaration (but undefined) - let/const → cannot use before declaration - Functions → behave differently based on type If this finally made hoisting click for you… 👉 Drop a ❤️ and comment "HOISTED" 👉 Follow Mohd Sharfuddin Khan for more bite-sized dev concepts that actually make sense

To view or add a comment, sign in

Explore content categories