Sub topic 3
let, const and Closures in Loops
This chapter assumes you already know for...in and for...of, closures, generators and async/await.
Per-iteration bindings
With let or const in the loop head, each iteration gets a fresh binding. Each closure therefore keeps its own value. With var, every iteration shares one binding.
const fns = [];
for (const x of [1, 2, 3]) fns.push(() => x);
console.log(fns.map(f => f())); // [1, 2, 3]
const fnsVar = [];
for (var y of [1, 2, 3]) fnsVar.push(() => y);
console.log(fnsVar.map(f => f())); // [3, 3, 3]Under the hood: Symbol.iterator and next()
for...of first calls obj[Symbol.iterator]() to get an iterator. It then calls next() on that iterator until a result has done: true.
const it = ['a', 'b'][Symbol.iterator]();
console.log(it.next()); // { value: 'a', done: false }
console.log(it.next()); // { value: 'b', done: false }
console.log(it.next()); // { value: undefined, done: true }break, continue and early exit
continue moves on to the next next() call. break, return and a thrown error all leave the loop early, and in each case the loop calls the iterator's return() method. For a generator, that runs its finally block.
function* counter() {
try { let n = 0; while (true) yield n++; }
finally { console.log('cleanup'); }
}
for (const n of counter()) {
if (n === 2) break;
console.log(n);
}
// 0, 1, cleanupMaking your own objects iterable
To make your own objects iterable, define a generator method under Symbol.iterator.
class Range {
constructor(start, end) { this.start = start; this.end = end; }
*[Symbol.iterator]() {
for (let i = this.start; i < this.end; i++) yield i;
}
}
console.log([...new Range(1, 4)]); // [1, 2, 3]Changing a collection while you loop
Array iteration tracks a live index. Elements you push during the loop get visited, and removing elements makes the loop skip some. Map and Set also visit entries added mid-loop. In for...in, a property deleted before the loop reaches it is skipped, and a property added during the loop may or may not be visited. The safe approach is to loop over a copy, such as [...arr].
for await...of
for await...of awaits each value from an async iterable. You can only use it inside an async function or at the top level of a module.
const delay = (ms, v) => new Promise(r => setTimeout(() => r(v), ms));
async function* ticks() {
yield await delay(100, 'first');
yield await delay(50, 'second');
}
(async () => {
for await (const t of ticks()) console.log(t);
})();
// first, secondPicking the right loop
| Task | Loop |
|---|---|
| Array or iterable values | `for...of` |
| Need the index or a custom step | classic `for`, or `for...of` with `entries()` |
| Object keys and values | `for...of` over `Object.entries(obj)` |
| Debug dump of keys, including inherited ones | `for...in` with `Object.hasOwn` |
| Side effect per element, no early exit | `forEach` |
| Async source | `for await...of` |
Exercise
A generator has a finally block, and a for...of loop over it exits with return inside a function. Does the finally block run, and why?
Show answer
Yes. Leaving the loop early through break, return or throw calls the iterator's return() method, and that runs the generator's finally block.