
Kar started this conversation 1 week ago.
Unexpected Closure Behavior in Loops: Same Value Each Time
I used a loop to register click handlers with a closure variable, but all handlers log the same value instead of each iteration's value. Example: js Copy code for (var i = 0; i < 3; i++) { button.addEventListener('click', function() { console.log(i); }); } All clicks output 3. Why?
Digiaru
Posted 1 week ago
Because var is function-scoped, each closure shares the same i, which is 3 after the loop ends. In effect, all handlers reference that final value RedditReddit+2Reddit+2LinkedIn+2. Fixes: • Use let to create block-scoped variables: js Copy code for (let i = 0; i < 3; i++) { button.addEventListener('click', () => console.log(i)); } • For older environments, use an IIFE to capture each i: js Copy code for (var i = 0; i < 3; i++) { ((j) => { button.addEventListener('click', () => console.log(j)); })(i); } This guarantees each callback retains the intended value.