Notes · 11.09.2026 · 142 views

let in a for-loop, still a trap

closures.js

Interviewers still paste a for-loop that logs 3, 3, 3. The fix is not “always use let”. The fix is understanding that the callback closes over the binding, not a snapshot of the number.

for (let i = 0; i < 3; i++) {
  setTimeout(() => console.log(i), 0);
}

That prints 0, 1, 2 because each iteration gets a fresh i. With var there is one binding for the whole function. If you need the old behaviour on purpose, copy the value into the callback’s arguments.

Comments · 6

Sam 08.09.2026 19:02

We still have this in a codebase that ships IE11 polyfills. Painful.

Lea 10.09.2026 09:41

The arguments trick is cleaner than an IIFE. Thanks.