Sub topic 18
Pitfalls and Best Practices
This chapter assumes you have worked through the earlier chapters. You should know the iterable and iterator protocols, generator functions and how they run, yield*, return() and try...finally cleanup, lazy pipelines, and async generators. Each section below names a common mistake, explains how it happens, and gives a fix you can apply.
Pitfall 1: Reusing a One-Shot Iterator
A generator object is both an iterator and an iterable. Its [Symbol.iterator]() method returns the generator object itself. Once that iterator finishes, it stays finished. A second loop over the same object gets nothing back, and no error tells you so.
function* evens(limit) {
for (let n = 0; n < limit; n += 2) yield n;
}
const seq = evens(6);
const total = [...seq].reduce((a, b) => a + b, 0);
const count = [...seq].length;
console.log(total); // 6
console.log(count); // 0, because seq was used up by the first spreadThe fix is to pass around an iterable that makes a new iterator on every pass, instead of passing around an iterator. You can do this with a class that has a generator method, or with a plain object:
function evensIterable(limit) {
return {
*[Symbol.iterator]() {
for (let n = 0; n < limit; n += 2) yield n;
}
};
}
const seq = evensIterable(6);
console.log([...seq].reduce((a, b) => a + b, 0)); // 6
console.log([...seq].length); // 3The same bug appears in hand-written collections whose [Symbol.iterator]() returns this and keeps the cursor on the collection. Keep the iteration state in the iterator object, never in the collection.
Pitfall 2: Expecting for...of to See the Return Value
for...of, spread, destructuring, and Array.from all stop as soon as they get done: true, and they throw away the value that comes with it. That means a generator's return value is lost to all of them. If the final value matters, yield it. If you need it as a separate result, read it with yield* inside another generator or call next() by hand.
Pitfall 3: Validation That Runs Too Late
A generator body does not start until the first next() call. Checks at the top of the body therefore run when someone starts consuming the generator, not when it is called. A bad argument then fails far from the call that caused it, or it just produces an empty sequence and no error.
function* rangeGen(start, end) {
for (let i = start; i < end; i++) yield i;
}
// Validate eagerly in a normal function, then hand off to the generator.
function range(start, end) {
if (!Number.isFinite(start) || !Number.isFinite(end)) {
throw new TypeError('range() needs two finite numbers');
}
return rangeGen(start, end);
}
const quiet = rangeGen('a', 5); // no error, and it yields nothing
console.log([...quiet]); // []
try {
range(1, Infinity); // throws right here, at the call site
} catch (e) {
console.log(e.message); // range() needs two finite numbers
}Splitting the work this way gives you eager errors and still keeps the generator's lazy behavior.
Pitfall 4: Eagerly Consuming an Infinite Sequence
Spread, Array.from, toArray(), destructuring with a rest element, and an unbroken for...of all read until done: true. On an infinite generator that never happens, so the program hangs or runs out of memory. Limit the sequence with take() or a break before you do anything eager. Do the same for helper chains. naturals().filter(n => n < 0).take(1) also hangs, because filter keeps pulling values while it looks for one that will never come.
Pitfall 5: Cleanup That Never Runs
for...of, destructuring, and spread call return() on the iterator when they stop early, through break, return, or a thrown error. Code that calls next() by hand gets no such help. If you stop early, you have to call return() yourself.
function* lines() {
console.log('open');
try {
yield 'line 1';
yield 'line 2';
} finally {
console.log('close');
}
}
const it = lines();
console.log(it.next().value); // open, then line 1
it.return(); // closeTwo more rules apply. First, if a generator never starts, its finally block never runs. Acquire resources inside the try, after the generator body has started. Second, do not yield inside finally. A yield there pauses the generator in the middle of cleanup, so return() gives back done: false and the resource stays open.
Pitfall 6: Mutating a Collection While Iterating It
Built-in iterators read the collection live. They do not work from a snapshot. An array iterator reads length again on every step, so if you push to the array inside the loop, the loop also visits the new items:
const arr = [1, 2, 3];
for (const x of arr) {
if (x === 1) arr.push(4);
console.log(x); // 1, 2, 3, 4
}If you push on every step, the loop never ends. Map and Set act the same way: entries added during the loop are visited, and deleted entries are skipped. If you need to change the collection, loop over a copy such as [...arr] or [...map.keys()].
Pitfall 7: Misusing for await...of
for await...of waits for one item at a time, in order. When you pass it an array of promises, it visits them in array order, not in the order they settle. It also does not start any work, so whatever runs at the same time is whatever you started before the loop.
const delay = (ms, v) => new Promise(r => setTimeout(() => r(v), ms));
(async () => {
const pending = [delay(300, 'slow'), delay(100, 'fast')];
for await (const v of pending) {
console.log(v); // slow (after 300 ms), then fast right after
}
})();There is a risk with this pattern. If a later promise in the array rejects while the loop is still waiting on an earlier one, nothing is handling that rejection yet, and the runtime may report an unhandled rejection. For a fixed batch of promises, use Promise.all or Promise.allSettled. Keep for await...of for real async sources such as async generators and streams, where each item is produced only when the loop asks for it. The paginate example in an earlier chapter is one of these.
Pitfall 8: Assuming Iterator Helpers Exist
Methods such as map, filter, take, and toArray on Iterator.prototype are from ES2025. Older browsers and older Node.js versions do not have them. On those runtimes, gen.map is undefined and calling it throws a TypeError. Check your target runtimes before you rely on them. Otherwise, load a polyfill or use small hand-written generator helpers like the ones from the lazy pipelines chapter. Note also that these helpers exist on iterators, not on iterables. Use Iterator.from(iterable) or call [Symbol.iterator]() first. And remember that the array methods with the same names are eager.
Choosing the Right Shape
Quick Reference
| Pitfall | Symptom | Fix |
|---|---|---|
| Reusing a generator object | Second pass is empty | Return an iterable that makes a fresh iterator |
| Relying on `return` value | Final value missing from loop or spread | `yield` it, or read it via `yield*` |
| Validation inside generator | Errors appear late or not at all | Validate in a wrapper function |
| Spreading infinite sequences | Program hangs | Limit with `take()` or `break` first |
| Manual `next()` with early stop | `finally` never runs | Call `return()` yourself |
| Mutating while iterating | Extra, skipped, or endless items | Iterate over a copy |
| `for await` over promise array | Unhandled rejections, settle order ignored | Use `Promise.all` / `allSettled` |
| Missing iterator helpers | `TypeError: ... is not a function` | Check support, polyfill, or hand-write helpers |
Exercise
A function getUsers() returns a generator object. One part of the code counts the users with [...users].length, and then a later for...of over the same users value logs nothing. Explain why, and give two ways to fix it.
Show answer
The generator object is a one-shot iterator. The spread reads it until done: true, and the finished generator then yields nothing to the for...of. Fix 1: call getUsers() again for each pass. Fix 2 (better): make getUsers() return an iterable, for example { *[Symbol.iterator]() { ... } }, so every loop gets a fresh iterator. Copying the values once into an array with const list = [...getUsers()] also works when the data is finite.
Exercise
A generator opens a resource and has finally { yield 'closing'; handle.close(); }. A consumer breaks out of a for...of early. What happens to the handle?
Show answer
The break calls return(), which runs the finally block. The block hits yield 'closing' and the generator pauses there, so return() gives back { value: 'closing', done: false }. The loop has already exited and never calls next() again, so handle.close() never runs and the handle leaks. Remove the yield from finally.
Exercise
Why might for await (const r of [fetchA(), fetchB()]) produce an unhandled rejection even though the loop is inside a try...catch?
Show answer
Both requests start before the loop does. If fetchB() rejects while the loop is still waiting on fetchA(), nothing is attached to the rejected promise yet, so the runtime may report it as unhandled before the loop reaches it. Use Promise.all or Promise.allSettled for a fixed batch like this.