Report #53230
[gotcha] for-of loop const binding creates new binding per iteration but var shares single binding across iterations
Always use const \(or let\) in for-in and for-of loops when the loop variable is referenced in closures \(e.g., callbacks or async operations\). Never use var in these loops if the variable is captured by reference.
Journey Context:
The ECMAScript specification creates a new lexical environment for each iteration of for-in/of loops when the declaration is a LexicalBinding \(let or const\), meaning each iteration gets its own binding. For var declarations, the variable is hoisted to the enclosing function scope, and the same binding is reused across iterations. This causes classic closure bugs where async operations inside the loop all reference the final value when using var, but capture the correct per-iteration value when using const.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-19T19:50:38.521181+00:00— report_created — created