JavaScript Interview Question: Understanding Closures and Execution Context

🚀 A Classic JavaScript Interview Question That Still Confuses Developers This question has come up in several frontend interviews I recently attended 👇 ❓ What will be the output? ``` for (var i = 0; i < 3; i++) { setTimeout(() => { console.log(i); }, 1000); } ``` 🤔 What most people expect: 0 1 2 ✅ Actual Output: 3 3 3 🔍 Why does this happen? 👉 `var` is function-scoped, not block-scoped That means: • Only one shared variable `i` exists • All callbacks refer to the same `i` • By the time `setTimeout` runs, the loop has completed • Final value of `i` becomes 3 So each callback prints 3 🧠 Key Concept This question tests: ✔ Closures ✔ Execution context ✔ Event loop behavior 💡 How to fix it? ✅ Using `let` (block scope) ``` for (let i = 0; i < 3; i++) { setTimeout(() => { console.log(i); }, 1000); } ``` ✔ Output: 0 1 2 ✅ Using IIFE (closure fix) ``` for (var i = 0; i < 3; i++) { ((index) => { setTimeout(() => { console.log(index); }, 1000); })(i); } ``` 🎯 Interview Insight This is not about syntax. It’s about understanding how JavaScript actually works under the hood. 💬 Have you been asked this in interviews? #JavaScript #FrontendDevelopment #CodingInterview #WebDevelopment #ReactJS #SoftwareDeveloper #FullStackDeveloper #TechInterview #JobSearch #Programming #LearnToCode #CareerGrowth #Developers #InterviewPreparation

To view or add a comment, sign in

Explore content categories