Advanced · 5 of 11 · 18 min read
Generators
Functions that pause and resume, the two-way channel yield opens, and the lazy sequences they make possible.
- Generators
Every other function runs to completion once you call it. A generator can stop in the middle, hand a value back, and continue later from exactly where it was — with all its local variables intact.
Calling one runs nothing
function* counter() {
console.log('started');
yield 1;
console.log('resumed');
yield 2;
console.log('finishing');
return 3;
}
const gen = counter(); // nothing is logged — the body has not run
console.log('created');
console.log(gen.next()); // "started" then { value: 1, done: false }
console.log(gen.next()); // "resumed" then { value: 2, done: false }
console.log(gen.next()); // "finishing" then { value: 3, done: true }
console.log(gen.next()); // { value: undefined, done: true }
Three things to read off that:
next()returns{ value, done }, never a bare value.yieldproducesdone: false;returnproducesdone: truewith its value.- Once finished, every further
next()gives{ undefined, true }. A generator is consumed once.
for...of and the spread consume it for you, and they ignore the return value:
console.log([...counter()]); // [1, 2] — the 3 from `return` is not included
for (const n of counter()) console.log(n); // 1 then 2
It is both an iterator and an iterable
const g = counter();
console.log(typeof g.next, typeof g[Symbol.iterator]); // "function" "function"
console.log(g[Symbol.iterator]() === g); // true — it returns itself
That is why a generator works directly in for...of, and it is the shortest correct way to make
your own type iterable:
class Playlist {
#tracks = ['a', 'b', 'c'];
*[Symbol.iterator]() {
yield* this.#tracks; // delegate to the array's own iterator
}
}
console.log([...new Playlist()]); // ["a", "b", "c"]
const [firstTrack] = new Playlist();
console.log(firstTrack); // "a"
But note the difference between a collection and a generator object: a collection hands out a fresh iterator each time, a generator object is one iterator.
const list = [1, 2];
console.log([...list], [...list]); // [1,2] [1,2]
const once = counter();
console.log([...once], [...once]); // [1,2] [] — exhausted
Laziness is the point
Values are produced on demand, so a sequence can be infinite without hanging:
function* naturals() {
let n = 1;
while (true) yield n++; // never terminates, and never blocks
}
function* take(iterable, count) {
let i = 0;
for (const value of iterable) {
if (i++ >= count) return;
yield value;
}
}
function* map(iterable, fn) {
for (const value of iterable) yield fn(value);
}
console.log([...take(map(naturals(), (n) => n * n), 5)]); // [1, 4, 9, 16, 25]
Five values were computed. The array equivalent would have to build every intermediate collection, which for an infinite source never finishes at all.
| Array pipeline | Generator pipeline | |
|---|---|---|
| Intermediate collections | one per step | none |
| Works on an infinite source | no | yes |
| Memory | the whole sequence | one value at a time |
| Can stop early | after building everything | immediately |
| Speed on small data | faster | slower — a call per value |
Generators are not an optimisation for a thousand-element array. They are the right tool when the sequence is huge, unbounded, or expensive to produce.
yield* delegates
It hands control to another iterable until that one is finished:
function* inner() {
yield 'b';
yield 'c';
}
function* outer() {
yield 'a';
yield* inner(); // not `yield inner()` — that would yield the generator object itself
yield 'd';
}
console.log([...outer()]); // ["a", "b", "c", "d"]
Which makes recursive walks very short:
function* walk(node) {
yield node.value;
for (const child of node.children ?? []) yield* walk(child);
}
const tree = { value: 1, children: [{ value: 2, children: [{ value: 3 }] }] };
console.log([...walk(tree)]); // [1, 2, 3]
Passing values back in
This is the part most people do not know: yield is an expression, and the argument you give
to next() becomes its value inside the generator.
function* conversation() {
const name = yield 'What is your name?';
const age = yield `Hello ${name}, how old are you?`;
return `${name} is ${age}`;
}
const chat = conversation();
console.log(chat.next().value); // "What is your name?" — no argument is used here
console.log(chat.next('Ana').value); // "Hello Ana, how old are you?"
console.log(chat.next(30).value); // "Ana is 30"
The first next() has nowhere to deliver a value — there is no suspended yield yet — so its
argument is always discarded. That off-by-one is the detail an interview is testing.
This two-way channel is what made generators the engine of co and early async libraries, and it
is the mechanism async/await was built on: await is yield, and the runtime is the thing
calling next() with the resolved value.
// What async/await is, roughly:
function run(genFn) {
const it = genFn();
return (function step(value) {
const { value: awaited, done } = it.next(value);
return done ? Promise.resolve(awaited) : Promise.resolve(awaited).then(step);
})();
}
run(function* () {
const a = yield Promise.resolve(1);
const b = yield Promise.resolve(a + 1);
console.log(a, b); // 1 2
});
return() and throw()
The two other ways to resume a suspended generator — from the outside.
function* resource() {
try {
yield 'open';
yield 'still open';
} finally {
console.log('cleaned up'); // runs on return(), on throw(), and on an early break
}
}
const r = resource();
console.log(r.next().value); // "open"
console.log(r.return('done')); // "cleaned up" then { value: "done", done: true }
for...of calls return() for you when the loop exits early, which is how a generator releases a
file handle or a cursor:
for (const state of resource()) {
console.log(state); // "open"
break; // "cleaned up" runs here
}
throw() injects an error at the suspension point, so the generator’s own try/catch sees it:
function* resilient() {
while (true) {
try {
yield 'working';
} catch (error) {
console.log('recovered from', error.message);
}
}
}
const w = resilient();
console.log(w.next().value); // "working"
console.log(w.throw(new Error('x')).value); // "recovered from x" then "working"
Async generators
for await...of over values that arrive later — the natural shape for pagination or a stream:
async function* pages(firstUrl) {
let url = firstUrl;
while (url) {
const page = await fetch(url).then((r) => r.json());
yield* page.items;
url = page.next;
}
}
// The consumer never learns that pagination exists:
// for await (const item of pages('/api/items')) console.log(item);
Where you would really use one
- ID generation and other unbounded sequences.
- Paging through an API without the caller knowing.
- Walking a tree with
yield*, which is shorter than building an array. - Streaming or chunking large data without loading all of it.
function* ids(prefix) {
let n = 0;
while (true) yield `${prefix}-${++n}`;
}
const nextId = ids('order');
console.log(nextId.next().value, nextId.next().value); // "order-1" "order-2"
They are a specialised tool. Most code should reach for an array method first and a generator when laziness is actually needed.
Common mistakes
Expecting the body to run on the call
Mistake. const g = setup(); and assuming the side effects happened.
Why it fails. Calling a generator function builds an object and runs nothing. The first
next() executes up to the first yield.
What to do instead. Consume it — for...of, spread, or an explicit next().
yield where yield* was meant
Mistake. yield inner() to splice in another generator’s values.
Why it fails. It yields the generator object as a single value, so the consumer gets one
opaque item instead of the sequence.
What to do instead. yield* inner().
Spreading an infinite generator
Mistake. [...naturals()].
Why it fails. The spread pulls until done, which never arrives: the tab freezes, then runs
out of memory.
What to do instead. Bound it first with take, or break out of a for...of.
Check yourself
3 questions from the bank on what you just read. Answering here does not affect your quiz history.
A generator hands out values one next() at a time, and also reports when it is done.
What does this log?
function* gen() {
yield 1;
yield 2;
}
const g = gen();
console.log(g.next().value, g.next().value, g.next().done);What does calling a generator function return?
Can you pass a value *into* a running generator?
Further reading
Everything above is meant to be enough on its own. These are for when you want the full specification of a detail.
Reaching the end of a lecture marks it as read.