Concept: Many beginners struggle with closures and asynchronous code. This exercise reveals a classic trap. The Setup: for (var i = 0; i < 3; i++) { setTimeout(() => { console.log(i); }, 100); } // Output: 3, 3, 3 (surprise!) Why? var is function-scoped, so the same i is shared across all loop iterations. By the time setTimeout runs, the loop has finished and i = 3 . The Fix (3 ways): // 1. Use let (block-scoped) for (let i = 0; i < 3; i++) { setTimeout(() => console.log(i), 100); } // Output: 0, 1, 2 // 2. IIFE closure with var for (var i = 0; i < 3; i++) { (function(j) { setTimeout(() => console.log(j), 100); })(i); }
// 3. .bind() method for (var i = 0; i < 3; i++) { setTimeout(console.log.bind(console, i), 100); } “Closures capture variables , not values. Always know your scope when working with async code.” You could turn this into a mini-quiz or a debugging exercise in the course — students remember the “why” when they see the unexpected output first. mosh javascript course free