Sub topic 3
Loops, Closures, and the Classic var Bug
This chapter assumes you know how block scope and function scope work, as covered in earlier chapters, and that you can write arrow functions.
Loops, Closures, and the Classic var Bug
A closure is a function that remembers the variables around it when it was created. A var loop counter is one binding shared by the whole function, so every closure created in the loop sees its final value. A let counter gets a fresh binding on each iteration.
const withVar = [];
for (var i = 0; i < 3; i++) {
withVar.push(() => i);
}
console.log(withVar.map(f => f())); // [3, 3, 3]
const withLet = [];
for (let j = 0; j < 3; j++) {
withLet.push(() => j);
}
console.log(withLet.map(f => f())); // [0, 1, 2]The same bug appears with setTimeout callbacks and event handlers created in a loop. Changing var to let fixes it.
Top-Level Variables and globalThis
In a classic script, such as a plain <script> tag in a browser, a top-level var becomes a property of the global object. A top-level let or const does not.
// Run as a classic script, not an ES module or Node.js CommonJS file
var g = 1;
let h = 2;
console.log(globalThis.g); // 1
console.log(globalThis.h); // undefinedAccidental Globals and Strict Mode
If you assign to a name you never declared, sloppy mode quietly creates a global. Strict mode throws a ReferenceError instead. ES modules and class bodies run in strict mode automatically.
function sloppy() {
total = 42; // no declaration: creates a global
}
sloppy();
console.log(globalThis.total); // 42
function strict() {
'use strict';
missing = 1;
}
try {
strict();
} catch (e) {
console.log(e.name); // 'ReferenceError'
}Which Keyword Should You Use?
| Keyword | Use it when | Notes |
|---|---|---|
| `const` | The binding never changes | Default choice. Objects it points to can still be changed. |
| `let` | You must reassign, such as counters or accumulators | Block-scoped, with a fresh binding per loop iteration |
| `var` | You maintain legacy code | Avoid it in new code |
Exercise
A loop for (var k = 0; k < 4; k++) { setTimeout(() => console.log(k), 0); } prints 4 four times. Why does this happen, and what is the smallest fix?
Show answer
All four callbacks close over the same function-scoped var k. By the time they run, k is 4. Changing var to let gives each iteration its own binding, so the loop prints 0, 1, 2, 3.
Exercise
In a classic browser script, const API = 'x' sits at the top level. What does window.API return?
Show answer
It returns undefined. A top-level const or let is not added to the global object. Only a top-level var or a function declaration is.