Generators and yield
A generator is a function that can pause in the middle, hand back a value, and resume later from exactly where it stopped.
function* declares a generator. Calling it runs nothing; it returns an iterator. Each next() runs until the next yield and pauses there, keeping every local variable alive. It is the short way to write everything the last lesson did by hand.
EXERCISE
1A Function That Pauses
Every function you have written so far runs to completion once called. A generator does not have to.
This is the genuinely new idea in the unit. An ordinary function starts, runs, and returns. It cannot stop halfway and be resumed later; when it returns, its local variables are gone.
A generator can.
The syntax and the first surprise:
function* countUp() {
console.log("starting");
yield 1;
console.log("resumed once");
yield 2;
console.log("resumed twice");
return 3;
}
const gen = countUp();
console.log("created");
// "created" -- "starting" has NOT printed
Calling a generator runs none of its body. It returns an iterator and waits. Nothing happens until you ask.
Each next runs to the following yield, then stops:
console.log(gen.next());
// starting
// { value: 1, done: false }
console.log(gen.next());
// resumed once
// { value: 2, done: false }
console.log(gen.next());
// resumed twice
// { value: 3, done: true }
console.log(gen.next());
// { value: undefined, done: true }
Read the interleaving carefully. The console.log lines inside the function ran between the next calls, not before them. Execution really did pause at each yield and pick up on the following line.
return sets done: true, and its value is skipped by loops:
function* g() {
yield 1;
return 99;
}
console.log([...g()]); // [ 1 ]
for (const v of g()) {
console.log(v); // 1
}
A for...of stops when done is true and ignores that final value. So return in a generator is for ending early, not for producing a result.
Local state survives the pause:
function* counter() {
let count = 0;
while (true) {
count += 1;
yield count;
}
}
const c = counter();
console.log(c.next().value); // 1
console.log(c.next().value); // 2
console.log(c.next().value); // 3
count is an ordinary local variable and it is still there three calls later. The generator's entire execution state, variables and position, is kept alive between calls. That is what makes while (true) safe here: it only advances when asked.
Which rewrites the last lesson in a fraction of the code:
const range = {
from: 1,
to: 3,
*[Symbol.iterator]() {
for (let i = this.from; i <= this.to; i++) {
yield i;
}
},
};
console.log([...range]); // [ 1, 2, 3 ]
No next, no { value, done }, no closure for the counter. The generator produces all of it.
Pro Tip: Write a generator whenever you would otherwise hand-write an iterator. The
{ value, done }protocol from the last lesson is worth understanding so that generators are not mysterious, but it is almost never worth typing. A generator is both an iterator and iterable, so a singlefunction*gives you everything.
EXERCISE
2Two-Way Communication, and Delegation
yield sends a value out, and it also receives one back, which turns a generator into something closer to a conversation.
yield is an expression, not a statement. It produces a value when the generator resumes.
Passing a value into next:
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?
console.log(chat.next("Ada").value); // Hello Ada, how old are you?
console.log(chat.next(36).value); // Ada is 36
The argument to next becomes the result of the yield that the generator was paused on. Note the offset: the first next cannot send anything useful, because the generator has not reached a yield yet.
A practical use, since that example is a toy:
function* runningTotal() {
let total = 0;
while (true) {
const amount = yield total;
total += amount;
}
}
const totals = runningTotal();
totals.next(); // prime it, discard the initial 0
console.log(totals.next(10).value); // 10
console.log(totals.next(5).value); // 15
console.log(totals.next(20).value); // 35
yield* delegates to another iterable:
function* letters() {
yield "a";
yield "b";
}
function* numbers() {
yield 1;
yield 2;
}
function* both() {
yield* letters();
yield* numbers();
yield "done";
}
console.log([...both()]); // [ 'a', 'b', 1, 2, 'done' ]
yield* hands control to another generator or any iterable until it is exhausted, then carries on. Without the star you would yield the generator object itself rather than its values.
It works on anything iterable, not only generators:
function* flatten(arrays) {
for (const arr of arrays) {
yield* arr;
}
}
console.log([...flatten([[1, 2], [3], [4, 5]])]); // [ 1, 2, 3, 4, 5 ]
And return and throw let you stop one from outside:
function* g() {
try {
yield 1;
yield 2;
} finally {
console.log("cleaning up");
}
}
const it = g();
console.log(it.next().value); // 1
console.log(it.return("early"));
// cleaning up
// { value: 'early', done: true }
The finally block runs, which means a generator can clean up after itself even when a consumer abandons it. A for...of that hits break calls return for you, so this happens automatically.
Pro Tip: Sending values in with
nextis the least used half of generators and the reason they can implement things a plain iterator cannot, such as a state machine or a task runner. Most of the time you will only yield outward, and that is fine. Knowing the channel exists explains how libraries like redux-saga work.
EXERCISE
3Where Generators Actually Get Used
Three real patterns, so the feature does not stay filed under interesting but unused.
Generators have a reputation for being clever and impractical. These three uses are neither.
One: generating ids and sequences.
function* idGenerator(prefix = "id") {
let n = 0;
while (true) {
n += 1;
yield `${prefix}-${n}`;
}
}
const nextId = idGenerator("user");
console.log(nextId.next().value); // user-1
console.log(nextId.next().value); // user-2
A counter in a closure would do the same, and this is worth comparing honestly rather than assuming the generator wins. The generator version reads as a sequence rather than as a function with hidden state, and it can be handed to anything that consumes an iterator.
Two: walking a tree without recursion in the consumer.
function* walk(node) {
yield node;
for (const child of node.children ?? []) {
yield* walk(child);
}
}
const tree = {
name: "root",
children: [
{ name: "a", children: [{ name: "a1" }] },
{ name: "b" },
],
};
for (const node of walk(tree)) {
console.log(node.name);
}
// root, a, a1, b
yield* recursing into itself flattens the whole tree into one sequence. The consumer writes a flat loop and never sees the recursion. Doing this without a generator means either building the full array first or passing a callback down.
Three: chunking a long job so it does not block.
function* processInChunks(items, size) {
for (let i = 0; i < items.length; i += size) {
yield items.slice(i, i + size);
}
}
async function run(items) {
for (const chunk of processInChunks(items, 500)) {
chunk.forEach(handle);
await new Promise((resolve) => setTimeout(resolve, 0));
}
}
This is Unit 4's yielding pattern with the chunk arithmetic moved out of the loop. The generator knows how to divide the work and the loop knows when to breathe, and neither has to know the other's job.
And one place they are the wrong answer:
// Over-engineered: the data is already an array
function* getNames(users) {
for (const user of users) {
yield user.name;
}
}
// Just use map
const names = users.map((user) => user.name);
If the collection is in memory and you want all of it, a generator adds a layer for nothing. The test is whether laziness buys you something: an unbounded sequence, work you might not finish, or a source too large to hold. If none of those apply, an array method is clearer.
