JavaScript Closures and Event Loop Gotcha

🧠 Most JavaScript devs answer this too fast — and get it wrong 👀 (Even after 2–5+ years of experience) ❌ No frameworks ❌ No libraries ❌ No Promises Just core JavaScript behavior. 🧩 Output-Based Question Closures + Event Loop for (var i = 0; i < 3; i++) { setTimeout(() => { console.log(i); }, 0); } ❓ What will be printed in the console? ❌ Don’t run the code 🧠 Think like the JavaScript engine A. 0 1 2 B. 3 3 3 C. 0 0 0 D. Nothing prints 👇 Drop ONE option only (no explanations yet 😄) 🤔 Why this matters Most developers know that: setTimeout runs later loops execute immediately But many don’t fully understand: how var is function-scoped how closures capture variables why async callbacks see final values When this mental model isn’t clear: bugs feel random logs don’t match expectations debugging becomes guesswork 💡 Strong JavaScript developers don’t guess outputs. They understand how variables live across time. #JavaScript #WebDevelopment #CodingChallenge #Closures #EventLoop #AsyncProgramming #JavaScriptEngine #DeveloperMindset #ProgrammingTips #CodeDebugging #SoftwareDevelopment #TechEducation #JavaScriptCommunity #FrontendDevelopment #LearningToCode

  • text, application

3 3 3 because javascript uses event loop to handle async tasks setTimeout goes to macrotask queue 3 loops done - now number updates to 3 after , 3 setTimeout runs, prints 3 3 3 as final value var updates scope value, using let solve problem

Like
Reply
See more comments

To view or add a comment, sign in

Explore content categories