Sub topic 18
Pitfalls and Best Practices
This chapter assumes you have read the earlier chapters on the iteration protocols, generators, cleanup, lazy pipelines, and async iteration. It collects the mistakes that come up most often in real code and gives a fix for each one.
Generator objects work only once
An iterable such as an array returns a fresh iterator each time Symbol.iterator is called. A generator object is an iterator whose Symbol.iterator method returns itself, so after one full pass it has nothing left to give.
function* count() {
yield 1;
yield 2;
}
const gen = count();
console.log([...gen]); // [ 1, 2 ]
console.log([...gen]); // [] (the generator is already finished)
const arr = [1, 2];
console.log([...arr], [...arr]); // [ 1, 2 ] [ 1, 2 ] (arrays create a new iterator each time)If you need to iterate more than once, pass around something that can produce new iterators, such as a class with a *[Symbol.iterator]() method or a function like count, and call it again for each pass. Don't pass a single generator object around. The same rule applies to hand-written collections: if Symbol.iterator returns this on the collection itself, the collection becomes one-shot.
Argument checks run late
A generator's body does not start until the first next() call. If you validate arguments inside the body, a bad call fails later, wherever the result is first consumed. To fail at the call site, validate in an ordinary function and then return the generator:
function range(start, end) {
if (!Number.isFinite(start) || !Number.isFinite(end)) {
throw new TypeError('range() needs finite numbers');
}
return rangeGen(start, end);
}
function* rangeGen(start, end) {
for (let i = start; i < end; i++) yield i;
}
console.log([...range(0, 3)]); // [ 0, 1, 2 ]
try {
range('a', 3); // throws immediately, not on first use
} catch (e) {
console.log(e.message); // range() needs finite numbers
}Quick reference
| Pitfall | What happens | Fix |
|---|---|---|
| Reusing a generator object | Second pass is empty | Call the generator function again, or expose `*[Symbol.iterator]()` |
| Expecting `for...of` to see `return` values | The value arrives with `done: true` and is dropped | `yield` the final value, or read it with `yield*` or a manual `next()` |
| Passing a value to the first `next(value)` | The value is ignored, because no `yield` is paused yet | Prime the generator with a bare `next()` first |
| Spreading an infinite sequence | The program hangs or runs out of memory | Limit it with `take` before `[...]`, `Array.from`, or `toArray()` |
| Opening resources without `finally` | A `break` or thrown error leaks the resource | Wrap the body in `try...finally` |
| Using `for...of` on an async iterable | `TypeError`: the object is not iterable | Use `for await...of` inside an async function |
| Calling iterator helpers on older runtimes | `map`/`take` are undefined on iterators | Check runtime support, or use your own generator helpers |
Best practices
- Prefer generator methods over hand-written
next()objects. Generators handledone, state, andreturn()for you. - Keep pipelines lazy until the last step, and convert to an array only once the size is bounded.
- Put cleanup in
finally. Keepyieldout of thefinallyblock, because it would pause cleanup partway through. - Document whether a function returns a reusable iterable or a one-shot iterator.
Exercise
A function getUsers() returns a generator object. The code runs const users = getUsers(); const count = [...users].length; for (const u of users) render(u); and nothing renders. Why, and what are two ways to fix it?
Show answer
The spread used up the generator, so the loop gets an iterator that is already done. One fix is to store the values once with const list = [...getUsers()] and use list for both the count and the loop. Another is to call getUsers() a second time for the loop, or have it return an object with a *[Symbol.iterator]() method so every pass gets a fresh iterator.
Exercise
Why does function* g(x) { if (x < 0) throw new Error('bad'); yield x; } const it = g(-1); not throw on the last statement?
Show answer
Calling a generator function only creates the generator object. The body, including the check, runs on the first it.next() call. Move the check into a plain wrapper function to make it throw when g is called.