JavaScript Hoisting Explained with Example

🧩 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

  • text

Output: undefined Reason: Inside the IIFE, var a is hoisted to the top of the function scope. So console.log(a) refers to the local a, which exists but isn’t assigned yet,hence undefined, not 10.

Undefined because Variable declared with var are hoisted to the top of their function scope , but their value is not hoisted

Undefined Reason: var is a function scope, hoisting issues

Undefined Because first function trying to find that variable in local scope and in that we already have hoisted variable

undefined , due to hoisting->global execution context created.

Iife create it own fs so no scope chaining

Like
Reply
See more comments

To view or add a comment, sign in

Explore content categories