⚡ Every Callback in Your Loop Is Using the Same Final Value, Not Its Own
A loop creates a callback for each iteration – a click handler, a `setTimeout`, a promise `.then()` – expecting each one to remember the value of the loop variable at the moment it was created, but every single callback ends up using the SAME final value instead, because of how `var` scoping and closures interact.
🔎 The Problem
for (var i = 0; i < buttons.length; i++) {
buttons[i].addEventListener('"'"'click'"'"', function () {
console.log('"'"'You clicked button number: '"'"' + i);
});
}
// Click ANY button, and the console always logs the SAME number -
// buttons.length (one past the last valid index) - because `var i` is
// scoped to the whole function, not to each loop iteration, so every
// closure captured a reference to the same `i`, and by the time any
// click actually happens, the loop has already finished and `i` holds
// its final value.
✅ Fix: Use `let` Instead of `var`
- Simply changing `var i` to `let i` fixes it completely – `let` creates a NEW binding for `i` on every iteration of the loop, so each closure captures its own separate value instead of sharing one.
- This is one of the clearest practical reasons `let`/`const` replaced `var` as the default choice in modern JavaScript – the per-iteration scoping isn’t a stylistic preference, it changes actual program behavior in exactly this situation.
⚠️ If You’re Stuck With `var` (Older Codebases)
- Wrap the loop body in an IIFE (immediately-invoked function expression) that takes `i` as a parameter – `(function (capturedI) { … })(i);` – which manually creates the fresh binding `let` gives you for free.
- `Array.prototype.forEach` sidesteps the problem entirely, since each callback invocation naturally gets its own parameter value rather than sharing a loop variable: `buttons.forEach(function (btn, i) { … });`.
A closure doesn’t remember what a variable WAS – it remembers the variable itself, and if every iteration shares one variable, every closure shares one memory.

