Understanding Hoisting in JavaScript with var, let, and const

🚀 JavaScript Learning Journey Topic Covered Today: Hoisting in JavaScript Hey everyone! 👋 Today I explored one of the most interesting concepts in JavaScript — Hoisting! Hoisting is JavaScript’s default behavior of moving declarations to the top of the current scope (before code execution). But the behavior varies depending on how you declare your variables — using var, let, or const. Here’s what I learned 👇 🔹 1. Hoisting with var When we use var, the variable declaration is hoisted, but not the initialization. That means you can access the variable before declaring it — but it will be undefined. console.log(a); // Output: undefined var a = 10; console.log(a); // Output: 10 ✅ Explanation: var a is hoisted to the top, but its value (10) is assigned later. 🔹 2. Hoisting with let Variables declared with let are also hoisted, but they stay in a Temporal Dead Zone (TDZ) until the declaration is encountered. console.log(b); // ❌ ReferenceError let b = 20; console.log(b); // Output: 20 ✅ Explanation: Accessing b before declaration throws a ReferenceError, since it’s not yet initialized. 🔹 3. Hoisting with const Similar to let, const is hoisted but also lives in the TDZ, and it must be initialized at the time of declaration. console.log(c); // ❌ ReferenceError const c = 30; console.log(c); // Output: 30 ✅ Explanation: const variables cannot be accessed before declaration, and must be initialized immediately. 💡 Key Takeaway: var → Hoisted and initialized as undefined. let & const → Hoisted but not initialized (TDZ applies). Always declare variables before using them to avoid unexpected errors! I’m really enjoying this JavaScript learning journey and understanding how these concepts make the language so dynamic. #JavaScript #LearningJourney #WebDevelopment #Coding #Frontend #Hoisting #LetVarConst #JavaScriptTips #LinkedInLearning

  • graphical user interface, text, application

To view or add a comment, sign in

Explore content categories