JavaScript Interview Question: Understanding Scope and setTimeout

One of the most common JavaScript interview questions that catches many beginners off guard! 👇 The Question: What will be the output? for (var i = 0; i < 3; i++) { setTimeout(() => console.log(i), 100); } The Expected Output: 0, 1, 2 The Actual Output: 3, 3, 3 Why does this happen? 🤔 1️⃣ Scope Issue: The keyword var is function-scoped. This means all the setTimeout callbacks are pointing to the same variable i. 2️⃣ The Delay: By the time the first setTimeout executes (after 100ms), the loop has already finished, and the value of i has become 3. The Fix: Use let 💡 Simply changing var to let solves the problem: ✔️ for (let i = 0; i < 3; i++) { setTimeout(() => console.log(i), 100); } Output: 0, 1, 2 Why? Unlike var, let is block-scoped. In every iteration of the loop, a new binding is created for i. Each setTimeout "remembers" its own version of i. Key Takeaway: Avoid var in modern JavaScript. Stick to let and const to prevent scope-related bugs! 🛡️ Did you get it right? Let me know in the comments! 👇 #JavaScript #WebDevelopment #CodingTips #InterviewPrep #Frontend #ReactJS #LearnToCode

See more comments

To view or add a comment, sign in

Explore content categories