var declares a binding scoped to the nearest function or module, ignoring intervening blocks. During scope setup, the binding is initialized to undefined, so it can be read before its declaration executes. section 7.3.1 section 7.3.2
Loop callbacks and scope
In a timer loop, replacing let i with var i means each callback sees the same binding; after the loop, each logs the final value. With let, each iteration has its own binding, so the callbacks log 0, 1, and 2. section 7.3.1
In practice:
- Treat var as a legacy keyword; most modern JavaScript developers prefer const and let. section 7.3.1
- Enforce avoiding var with ESLint’s no-var rule. section 7.3.1
