JavaScript Bug: Closure Gotcha with setTimeout and Loop

🔍 JavaScript Bug You Might Have Seen (setTimeout + loop) You write this code: for (var i = 1; i <= 3; i++) { setTimeout(() => { console.log(i); }, 1000); } You expect: 1 2 3 But you get: 4 4 4 This happens because of closure 📌 What is a Closure? 👉 A closure is a function along with its lexical environment. Not clear? No problem. Here’s a simpler version: 👉 A closure is a function along with the variables it remembers from where it was created. In this case: The function inside setTimeout 👉 remembers the SAME i variable And when it executes: 👉 Loop has already finished → i = 4 So all logs print: 4, 4, 4 How to fix it? ✔ Use let (creates a new variable per iteration) for (let i = 1; i <= 3; i++) { setTimeout(() => { console.log(i); }, 1000); } ✔ Or create a new scope manually for (var i = 1; i <= 3; i++) { (function(i) { setTimeout(() => { console.log(i); }, 1000); })(i); } 💡 Takeaway: ✔ Closures remember variables, not values ✔ var shares the same scope → leads to bugs ✔ let creates a new scope per iteration 👉 If you understand closures, you’ll avoid some very tricky bugs. 🔁 Save this for later 💬 Comment “closure” if this made sense ❤️ Like for more JavaScript deep dives #javascript #frontend #codingtips #webdevelopment #js #developer

To view or add a comment, sign in

Explore content categories