Generators: function*, yield and next

A generator is a function that can pause in the middle and continue where it stopped. It is written with an asterisk after the word function, and it pauses at every yield. Calling it does not run the body: it builds an iterator, and each call of next on that iterator runs the body up to the next yield and hands the value back.

The point is laziness. A generator may describe a sequence that is too long to build, or one whose values are only needed one at a time, and the consumer decides when to ask for the next. This lesson shows the protocol by hand, the loops that consume a generator without a next in sight, the values that travel back into the paused function, and the delegation that lets one generator hand its turn to another.

function* and yield

Each call of next returns an object with two fields: the value of the yield that was reached, and a flag that says whether the generator has finished. A generator with three yield statements therefore needs four calls of next before the flag stays true: the last call runs the code after the final yield.

function* numbers() { yield 1; yield 2; return 3; } const iterator = numbers(); let step = iterator.next(); console.log(`value=${step.value} done=${step.done}`); step = iterator.next(); console.log(`value=${step.value} done=${step.done}`); step = iterator.next(); console.log(`value=${step.value} done=${step.done}`); step = iterator.next(); console.log(`value=${step.value} done=${step.done}`); console.log('the generator object itself:', typeof iterator.next, typeof iterator[Symbol.iterator]);

node yield.js

value=1 done=false
value=2 done=false
value=3 done=true
value=undefined done=true
the generator object itself: function function

The third call returned the value of the return statement and set done at the same time, so a for...of loop would stop before it and never see the three. The fourth call has nothing left and reports undefined for ever. The last line is the quiet connection to the next lesson: a generator object is both an iterator, with next, and an iterable, with a Symbol.iterator that returns itself.

Iteration with for...of

The loop hides the calls of next: it asks for one value per turn and stops when the flag says done. The spread syntax does the same and collects everything, which is fine for a short sequence and impossible for an endless one. The program below uses the loop on an endless generator and stops it with a break, which is what laziness buys.

function* numbers() { yield 1; yield 2; } for (const value of numbers()) { console.log('from for...of:', value); } console.log('spread:', [...numbers()].join(',')); function* natural() { let value = 1; while (true) { yield value; value += 1; } } const taken = []; for (const value of natural()) { if (value > 4) { break; } taken.push(value); } console.log('lazy and endless:', taken.join(','));

node iteration.js

from for...of: 1
from for...of: 2
spread: 1,2
lazy and endless: 1,2,3,4

The loop and the spread both received the two values and neither one saw a next call. The endless generator is the same code as an endless loop until the consumer stops asking, which is why it is safe inside a for...of with a break and fatal inside a spread. A generator that reads lines of a file or pages of an API works the same way: only the values that were asked for are ever produced.

Values in, values out

An argument of next becomes the value of the yield that is currently paused, so a generator can be a conversation rather than a list. The first call only starts the body and its argument is discarded. A generator may also be closed early with return, and its finally blocks run before it finishes.

function* conversation() { const name = yield 'name?'; const age = yield `hello ${name}`; return `${name} is ${age}`; } const talk = conversation(); console.log(talk.next().value); console.log(talk.next('ada').value); console.log(talk.next(36).value); function* cleanup() { try { yield 'open'; yield 'open again'; } finally { console.log('the finally block runs on return'); } } const guarded = cleanup(); console.log(guarded.next().value); const closed = guarded.return('stopped'); console.log(`value=${closed.value} done=${closed.done}`); console.log('the generator refused the name:', conversation().next('ignored').value);

node values.js

name?
hello ada
ada is 36
open
the finally block runs on return
value=stopped done=true
the generator refused the name: name?

The string ada travelled into the paused generator and came back inside the next sentence it yielded, and 36 finished the conversation. The finally block ran when return closed the generator, which is the place to release a file handle or a lock a generator might hold. The last line is the rule about the first call: the argument of next has no yield to go to yet, so a generator that is not running discards it.

Delegation with yield*

yield* hands the turn to another iterable for as long as it produces values, and then continues with the rest of the body. Any iterable will do, so an array, a string or another generator are all valid on the right of the star. This is how a generator of a large sequence is assembled from smaller ones.

function* inner() { yield 1; yield 2; } function* outer() { yield 0; yield* inner(); yield 3; } console.log([...outer()].join(',')); function* lines(text) { yield* text.split('\n'); } const result = []; for (const line of lines('one\ntwo\nthree')) { result.push(line.toUpperCase()); } console.log(result.join('|'));

node delegate.js

0,1,2,3
ONE|TWO|THREE

The outer generator produced the zero, then every value of the inner one, then the three, and the consumer saw a single sequence. The second generator is a thin wrapper over an array, which is enough to make the point: yield* accepts anything a for...of accepts, because both use the same protocol. The next lesson takes that protocol apart and shows how to make any object work with it.

Exercises

  1. Add a fourth yield to numbers in yield.js. How many calls of next does the generator need now, and which one returns the return value?
  2. Replace the loop in iteration.js with [...natural()]. What happens, and why is that not a bug in the generator?
  3. Pass a value to the first next of conversation in values.js. Where does that value go, and what does the generator do with it?
  4. Remove the finally block from cleanup. Which line of the output disappears?
  5. Write a generator that yields the values of two arrays one after the other with yield*. How many values does the consumer receive?

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What does calling a generator function return?

    Answer

    An iterator object, without running the body

    The body runs on the first next call, so the call itself only builds the iterator.

  2. What does next return?

    Answer

    An object with a value and a done flag

    The two fields say what was yielded and whether the generator has finished.

  3. What does this program print? function* g() { yield 1; yield 2; } const it = g(); console.log(it.next().value, it.next().value, it.next().done);

    Answer

    1 2 true

    Two yields give two values and the third call finds nothing left, so done is true.

  4. What does for...of do with the value of a return statement in a generator?

    Answer

    It stops before it, so the value is never seen

    The return sets done at the same time, and a loop only uses values whose done is false.

  5. What does this program print? function* g() { yield "a"; return "b"; } console.log([...g()].join(","));

    Answer

    a

    The spread stops at the return value, so only the yielded item reaches the array.

  6. Why is an endless generator safe inside a for...of with a break?

    Answer

    Values are produced only when they are asked for

    The generator is lazy: it runs up to the next yield on demand, and a break simply stops asking.

  7. What does this program print? function* g() { const x = yield 1; return x; } const it = g(); it.next(); console.log(it.next(5).value);

    Answer

    5

    The argument of the second next becomes the value of the paused yield, and the return hands it back.

  8. Where does the argument of the first next call go?

    Answer

    Nowhere: there is no paused yield to receive it yet

    The body starts on the first call and runs to the first yield, so the argument arrives before anything waits for it.

  9. What does yield* accept on its right-hand side?

    Answer

    Any iterable, such as an array or another generator

    The star uses the same iteration protocol as for...of, so anything that protocol accepts works.

  10. What does this program print? function* g() { yield* [1, 2]; yield 3; } console.log([...g()].join(","));

    Answer

    1,2,3

    The delegated array gives its two values and the body continues with its own yield.

The code on this page was run with Node.js 24.22.1 and linted with ESLint 10.14.0 on Alpine Linux 3.24.3 (x86_64) in a Docker container.

Article author: Arthur Isaev

Banner image