JavaScript Closures and Async Timing in Frontend Interviews

🚀 Frontend Interview Prep — Closures + Async Let’s test your real understanding of JavaScript 👇 ❓ Question for (var i = 0; i < 3; i++) { setTimeout(() => { console.log(i); }, 1000); } -> What will be the output? 🤔 Think Before You Scroll Will it print: A) 0 1 2 B) 3 3 3 C) 0 0 0 ✅ Answer -> B) 3 3 3 🧠 Explanation -> var is function-scoped, not block-scoped -> By the time setTimeout runs: Loop is already finished i becomes 3 -> All callbacks share the same reference of i ✅ Fix #1 — Use let for (let i = 0; i < 3; i++) { setTimeout(() => { console.log(i); }, 1000); } -> Output: 0 1 2 -> Because let is block-scoped ✅ Fix #2 — Closure (IIFE) for (var i = 0; i < 3; i++) { ((j) => { setTimeout(() => { console.log(j); }, 1000); })(i); } -> Creates a new scope for each iteration => Real Interview Insight Interviewers are not testing syntax… -> They are testing your understanding of: Closures Scope Event loop 💡 Pro Insight -> Whenever async + loop is involved… -> Think about scope & timing 🎯 Key Takeaway JavaScript doesn’t behave how it “looks”… -> It behaves how it’s executed Master these small concepts… -> And you’ll crack most frontend interviews #FrontendDevelopment #JavaScript #InterviewPrep #CodingTips #WebDevelopment #Developers #LearnInPublic #DeveloperJourney

  • No alternative text description for this image

To view or add a comment, sign in

Explore content categories