What is a Generator function?

A generator function (function*) returns an iterator whose code runs lazily: each next() call resumes the function until the next yield, which hands out a value and pauses again, keeping all local state between calls.

How it works

  • Calling a generator does not run its body; it returns a generator object.
  • gen.next() runs until the next yield value and returns { value, done: false }.
  • When the function returns, you get { value: returnValue, done: true }.
  • Generators are iterable, so they work with for...of, spread and destructuring.

Two-way communication

  • gen.next(x) sends x back in as the result of the paused yield expression.
  • gen.return(v) finishes the generator (running finally blocks).
  • gen.throw(err) throws an error at the paused yield.

Use cases

  • Lazy and infinite sequences: ids, Fibonacci, pagination, without building huge arrays.
  • Custom iteration for your own data structures (*[Symbol.iterator]()).
  • Pipelines that process data step by step (map/filter/take over streams of values).
  • Delegation with yield* to compose generators, e.g. walking a tree.
  • Historically, async control flow (redux-saga, and the idea behind async/await).

Iterator helpers

Modern engines add methods directly on iterators (map, filter, take, drop, toArray, ...), so generator pipelines read like array chains without creating intermediate arrays. Check support before relying on them in older browsers.

Code example

js
1function* idGenerator(prefix = "id") {
2 let n = 1;
3 while (true) yield `${prefix}-${n++}`; // infinite, but lazy
4}
5const ids = idGenerator("user");
6console.log(ids.next().value, ids.next().value); // user-1 user-2
7
8// Finite generator: works with for...of and spread
9function* countdown(from) {
10 try {
11 while (from > 0) yield from--;
12 return "liftoff";
13 } finally {
14 console.log("cleanup runs on finish or early exit");
15 }
16}
17console.log([...countdown(3)]); // [3, 2, 1] (the return value is not included)
18
19// Two-way: values sent in with next(x)
20function* runningTotal() {
21 let total = 0;
22 while (true) total += (yield total) ?? 0;
23}
24const acc = runningTotal();
25acc.next(); // start
26acc.next(5);
27console.log(acc.next(10).value); // 15
28
29// yield* delegation: walk a tree lazily
30function* walk(node) {
31 yield node.name;
32 for (const child of node.children ?? []) yield* walk(child);
33}
34const tree = { name: "src", children: [{ name: "app", children: [{ name: "page.tsx" }] }, { name: "lib" }] };
35console.log([...walk(tree)]); // ["src", "app", "page.tsx", "lib"]
36
37// Take the first 5 even squares from an infinite sequence without building arrays
38function* naturals() {
39 let n = 1;
40 while (true) yield n++;
41}
42const firstFive = [];
43for (const n of naturals()) {
44 if ((n * n) % 2 === 0) firstFive.push(n * n);
45 if (firstFive.length === 5) break; // break also triggers cleanup
46}
47console.log(firstFive); // [4, 16, 36, 64, 100]

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the JavaScript set.

Open in study app