JavaScript Interview Trap: var vs let Scope

💡 JavaScript Interview Trap — Can You Predict the Output? for (var i = 0; i < 5; i++) { setTimeout(function () { console.log(i); }, 1000); } 🤔 What do you think this will print? Most developers expect: 👉 0 1 2 3 4 But the actual output is: 👉 5 5 5 5 5 🚨 Why does this happen? Because: var is function-scoped, not block-scoped By the time setTimeout runs, the loop has already completed So i becomes 5 for all executions 🧠 Fix it using let (block scope): for (let i = 0; i < 5; i++) { setTimeout(function () { console.log(i); }, 1000); } ✅ Output: 👉 0 1 2 3 4 🔥 Key Takeaways: Understand var vs let scope Know how closures work Be careful with async functions inside loops 📌 This is one of the most common JavaScript interview questions! #JavaScript #WebDevelopment #CodingInterview #Frontend #AsyncJavaScript #LearnToCode

Another question :- how would you do this without changing var into let? Answer:- by enclosing setTimeout into IIFE.

Like
Reply

To view or add a comment, sign in

Explore content categories