So… why does this code NOT throw an error? 🤔 The reason is HOISTING ! console.log(a); var a = 10; 👉 JavaScript moves variable and function declarations to the top of the code before execution. This is called Hoisting. When JavaScript sees the code, it actually understands it like this 👇 var a; console.log(a); a = 10; 🤯 What’s happening here? The variable a is declared first But its value (10) is assigned later So when console.log(a) runs, a exists but has no value yet That’s why the output is: 👉 undefined 👉 NOT an error ❌ ⚠️ Important thing to remember: var is hoisted and initialized with undefined let and const are hoisted too, but NOT initialized This happens because let and const stay in the Temporal Dead Zone until they are declared. 🚀 Why hoisting matters? ✅ Helps you avoid unexpected bugs ✅ Makes your code more predictable ✅ Frequently asked in JavaScript interviews Follow BhaviDigital for beginner-friendly frontend & backend content 🚀 #JavaScript #WebDevelopment #Frontend #LearnJavaScript #CodingJourney #BhaviDigital
JavaScript Hoisting Explained: Why var is Hoisted but Not let or const
More Relevant Posts
-
Day 57/100 — The JavaScript Event Loop finally made sense 🔄 For a long time I used setTimeout, Promise, and async/await… but honestly — I never truly understood why JavaScript behaves the way it does. Today I learned about the Event Loop — and everything clicked. JavaScript is single-threaded. So how does it still handle multiple tasks at once? Because of 3 things working together: 🧠 Call Stack – where code runs step by step 📬 Web APIs – timers, DOM events, fetch requests handled outside JS 📋 Callback Queue / Microtask Queue – waiting tasks And the Event Loop keeps checking: “Is the call stack empty? If yes → push the next task.” The biggest surprise for me: console.log("Start"); setTimeout(() => console.log("Timeout"), 0); Promise.resolve().then(() => console.log("Promise")); console.log("End"); Output is NOT what beginners expect: Start End Promise Timeout Because microtasks (Promises) run before macrotasks (setTimeout) 💡 Realization: JavaScript is not slow… I just didn’t understand its scheduling system. Now async code feels predictable instead of magical. Learning fundamentals is like turning chaos into logic. #100DaysOfCode #JavaScript #EventLoop #AsyncJS #WebDevelopment #LearningInPublic
To view or add a comment, sign in
-
-
🗓️ Day 61/100 – Understanding the JavaScript Scope Chain Today I finally understood why sometimes variables work… and sometimes they suddenly don’t. The answer = Scope Chain At first I thought JavaScript just “searches everywhere” for a variable. But no — it actually follows a very specific path. JavaScript looks for variables in this order: 1️⃣ Current function scope 2️⃣ Parent function scope 3️⃣ Global scope It climbs upward step-by-step until it finds the variable. This is called the scope chain. --- Example idea: A function inside a function inside a function… The inner function can access outer variables But the outer function cannot access inner variables So access flows inside → outside Never outside → inside --- Big realization today 💡 Most bugs I faced earlier were not logic mistakes… They were scope mistakes. If you understand scope chain: • Closures make sense • Hoisting becomes clearer • Debugging becomes easier JavaScript stops feeling random — It starts feeling predictable. Slowly the language is revealing its rules, not magic. #100DaysOfCode #JavaScript #Scope #WebDevelopment #Frontend #LearningInPublic
To view or add a comment, sign in
-
-
🚀 JavaScript Magic: Why "Undefined" is actually a Feature, not a Bug! I just had a "Wow" moment diving into the JavaScript Execution Context, and it changed how I look at my code. Ever wondered why you can console.log a variable before you even declare it, and JavaScript doesn't lose its mind? 🤯 🧠 The Secret: Two-Phase Execution When your code runs, JavaScript doesn't just start at line 1. It takes two passes: 1.Memory Creation Phase: JS scans your code and allocates space for all variables and functions. 2. Execution Phase: It runs the code line-by-line. ⚡ The var Behavior (Hoisting) If you use var, JavaScript initializes it as undefined during the memory phase. Result: You can log it early. No error, just a quiet undefined. It’s like the variable is there, but its "suit" hasn't arrived yet. 🛑 The let & const Twist (TDZ) Try the same thing with let or const, and the engine throws a ReferenceError. Why? The Temporal Dead Zone (TDZ). While let and const are also "hoisted," they aren't initialized. They stay in a "dead zone" from the start of the block until the moment the code actually hits the declaration. The Lesson: JavaScript isn't just reading your code; it's preparing for it. Understanding the Execution Context makes debugging feel like having X-ray vision. 🦸♂️ Have you ever been bitten by the Temporal Dead Zone, or do you still find yourself reaching for var out of habit? Let’s discuss! 👇 #JavaScript #WebDevelopment #CodingTips #Frontend #Programming101
To view or add a comment, sign in
-
Why JavaScript doesn't crash when you call a function before defining it. 🧠 I recently dove deep into the "Execution Context" of JavaScript, and the concept of Hoisting finally clicked. If you’ve ever wondered why this code works: greet(); function greet() { console.log("Hello LinkedIn!"); } ...the answer lies in how the JS Engine treats your code before it even runs a single line. The Two-Phase Secret: Memory Creation Phase: Before the "Thread of Execution" starts, JavaScript scans your code and allocates memory for variables and functions. Functions are stored in their entirety in the Variable Environment. Variables (var) are stored as undefined. Code Execution Phase: Now, the engine runs the code line-by-line. Because the function is already sitting in the memory component, calling it on line 1 is no problem! The Key Takeaway: Hoisting isn't "moving code to the top" (that’s a common myth). It’s actually the result of the Memory Creation Phase setting aside space for your declarations before execution starts. Understanding the "how" behind the "what" makes debugging so much easier. #JavaScript #WebDevelopment #CodingTips #Hoisting #ProgrammingConcepts
To view or add a comment, sign in
-
-
Ever wonder what actually happens when you hit "run" on your JavaScript code? It’s not magic—it’s the Execution Context, the environment where JavaScript runs your code. Most developers use JavaScript every day, but understanding the "under the hood" mechanics like the Call Stack and Memory Phase is what separates a coder from an engineer. In this carousel, I break down: The Global vs. Function Execution Context — How JS sets the stage when it starts or when a function is called. The Creation Phase — Why var becomes undefined while let and const stay uninitialized. The Call Stack — The "Last In, First Out" (LIFO) rule that manages your execution order. The 'this' Keyword — How its value changes based on whether you are in a global, object, or arrow function context. Understanding these fundamentals makes debugging easier and your code more efficient. Which JS concept took you the longest to "click"? Let’s discuss in the comments! 👇 #JavaScript #WebDevelopment #CodingTips #SoftwareEngineering #TechEducation #FrontendDevelopment
To view or add a comment, sign in
-
🧩 JavaScript Output-Based Question (Hoisting) ❓ What will be printed? 👉 Comment your answer below (Don’t run the code ❌) Correct Output : undefined 🧠 Why this output comes? (Step-by-Step) 1️⃣ Function creates its own scope The IIFE (Immediately Invoked Function Expression) creates a new local scope. 2️⃣ var a is hoisted inside the function Inside the function, this line: var a = 20; is treated by JavaScript as: var a; // hoisted a = 20; // assigned later So when console.log(a) runs: • the local a exists • but it is not initialized yet That’s why: undefined is printed instead of 10. 3️⃣ Local a shadows the global a The global a = 10 is completely ignored inside the function because the local var a shadows it. 🔑 Key Takeaways ✔️ var declarations are hoisted ✔️ Initialization happens later ✔️ Local variables shadow global ones ✔️ Hoisting bugs often appear inside functions Hoisting doesn’t move code — it moves declarations. #JavaScript #Hoisting #InterviewQuestions #FrontendDeveloper #MERNStack #WebDevelopment
To view or add a comment, sign in
-
-
🌙 Evening Post — Function Reference vs Function Call (Very Important!) This morning’s code was: function show() { return "Hello"; } console.log(show); console.log(show()); 💡 Correct Output : [ Function : show ] Hello (Exact formatting may vary by browser, but the meaning is the same.) 🧠 Simple Explanation : 🔹 Line 1: console.log(show); Here, we are NOT calling the function. show refers to the function itself JavaScript prints the function definition This is called a function reference So the output shows something like: [ Function : show ] 👉 You’re telling JS: “Show me the function, not run it.” 🔹 Line 2: console.log(show()); Now the function IS called. show(); // returns "Hello" So this becomes: console.log("Hello"); ✔ Output: Hello 🎯 Key Takeaways : show → function reference (no execution) show() → function execution Functions in JS are values, just like numbers or strings You can pass functions around without calling them 📌 This difference is very important in: callbacks event handlers React props higher-order functions 💬 Your Turn Did you already know this difference? 😄 Comment “Clear now ✅” or “Didn’t notice this before 🤯” #JavaScript #LearnJS #FrontendDevelopment #CodingInterview #Functions #TechWithVeera #WebDevelopment
To view or add a comment, sign in
-
-
JavaScript Notes to Escape Tutorial Hell (20/20) 🏁 It’s a wrap. 20 Days. 20 Concepts. One Goal: Mastering the Internals. I started this series to document my own journey from "copy-pasting code" to understanding how the JS Engine actually thinks. Today, I’m sharing the Final Compilation. This isn't just a slide deck. It’s a 350+ Page Handbook covering everything we’ve learned, PLUS exclusive new chapters on Promises, Async/Await, and Promise APIs. The Full Roadmap Inside: - The Basics Execution Context, Call Stack, Hoisting - The Tricky Stuff Closures, Scope Chain, this, let vs var - The Architecture Event Loop, Callback Queue, Microtask Queue, JIT Compilation - Functional JavaScript Higher-Order Functions, map, filter, reduce - The Grand Finale Callback Hell, Promises, Async/Await, Error Handling 🔗 Why a Drive Link? The file is massive (high-quality visuals for every concept). LinkedIn won't let me upload it directly. How to get it? 1. Connect (so I can DM you). 2. Comment "Note" below. I’ll send the Google Drive link straight to your inbox. 📩 This series made me fall in love with JavaScript. I hope this handbook does the same for you. #JavaScript #WebDevelopment #CodingResources #SoftwareEngineering #FrontendDeveloper #Promises #AsyncAwait #LearningInPublic
To view or add a comment, sign in
-
Most people think functions "forget" everything once they finish running. Closures change the rules! While revising JavaScript fundamentals today, closures finally made sense to me. Normally, variables are garbage collected after execution. But closures allow inner functions to access outer variables even after the outer function has finished. In simple words, the inner function “remembers” its outer scope. 💬 Why this matters: • Private Variables : Closures let us protect data by keeping variables inaccessible from outside. • Persistent State : They allow functions to remember values without relying on global variables. • Event Handlers : They help UI elements remember what action to perform later. • Modules : They help organize code and prevent naming conflicts in larger applications. What’s one JavaScript concept that recently clicked for you? 👇 #JavaScript #WebDevelopment #Closures #LearningJourney
To view or add a comment, sign in
-
Explore content categories
- Career
- Productivity
- Finance
- Soft Skills & Emotional Intelligence
- Project Management
- Education
- Technology
- Leadership
- Ecommerce
- User Experience
- Recruitment & HR
- Customer Experience
- Real Estate
- Marketing
- Sales
- Retail & Merchandising
- Science
- Supply Chain Management
- Future Of Work
- Consulting
- Writing
- Economics
- Artificial Intelligence
- Employee Experience
- Workplace Trends
- Fundraising
- Networking
- Corporate Social Responsibility
- Negotiation
- Communication
- Engineering
- Hospitality & Tourism
- Business Strategy
- Change Management
- Organizational Culture
- Design
- Innovation
- Event Planning
- Training & Development