JavaScript Scope Challenge: Can You Solve It?

🧠 Developer Challenge – Can You Solve This in 10 Seconds? Many developers fail this simple JavaScript logic test during interviews. What will be the output of this code? 👇 for (var i = 0; i < 3; i++) { setTimeout(() => { console.log(i); }, 1000); } 🧠 Options: A️⃣ 0 1 2 B️⃣ 3 3 3 C️⃣ 0 0 0 D️⃣ 1 2 3 👇 Comment your answer before reading the explanation. . . . ✅ Answer: B️⃣ 3 3 3 💡 Reason: var is function-scoped, not block-scoped. By the time setTimeout runs, the loop has already finished and i becomes 3. So the callback prints 3 three times. 🔧 Correct Version Using let: for (let i = 0; i < 3; i++) { setTimeout(() => { console.log(i); }, 1000); } Output: 0 1 2 📌 Learning: Understanding JavaScript scope and closures is crucial for writing predictable asynchronous code. 💬 Did you get it right? Comment YES or your answer below! #JavaScript #Angular #FrontendDevelopment #CodingChallenge #SoftwareEngineering #Developers #TechLearning

To view or add a comment, sign in

Explore content categories