JavaScript Generators
A generator is a special function that can pause in the middle and resume later, producing a sequence of values one at a time. You define it with function* and pause it with yield. Generators are the easiest way to create custom iterators, lazy sequences and step-by-step processes.
A first generator
Calling a generator function doesn't run its body. It returns a generator object, which is an iterator: each call to next() runs the body until the next yield, and returns { value, done }:
function* trafficLight() {
console.log(" (starting)");
yield "green";
yield "yellow";
yield "red";
console.log(" (finished)");
}
const light = trafficLight(); // nothing runs yet
console.log(light.next());
console.log(light.next());
console.log(light.next());
console.log(light.next());
console.log(light.next()); // stays done (starting)
{ value: 'green', done: false }
{ value: 'yellow', done: false }
{ value: 'red', done: false }
(finished)
{ value: undefined, done: true }
{ value: undefined, done: true }
Between next() calls, the generator is frozen — its local variables and position are kept.
Generators are iterable
Generator objects work with everything that consumes iterables: for…of, spread, destructuring, Array.from:
function* countdown(from) {
for (let i = from; i > 0; i--) {
yield i;
}
}
for (const n of countdown(3)) console.log(n);
console.log([...countdown(5)]);
const [first, second] = countdown(10);
console.log(first, second);3
2
1
[ 5, 4, 3, 2, 1 ]
10 9
Infinite and lazy sequences
Because values are produced only when requested, a generator can describe an infinite sequence. Small helper generators can then take, filter and transform values lazily:
function* fibonacci() {
let [a, b] = [0, 1];
while (true) {
yield a;
[a, b] = [b, a + b];
}
}
function* take(iterable, n) {
if (n <= 0) return;
for (const value of iterable) {
yield value;
if (--n === 0) return;
}
}
function* filter(iterable, test) {
for (const value of iterable) if (test(value)) yield value;
}
console.log([...take(fibonacci(), 10)]);
console.log([...take(filter(fibonacci(), (n) => n % 2 === 0), 5)]);[
0, 1, 1, 2, 3,
5, 8, 13, 21, 34
]
[ 0, 2, 8, 34, 144 ]
Only as many Fibonacci numbers as needed are ever calculated.
Sending values in, and return
next(value) resumes the generator and makes the paused yield expression evaluate to value. This turns a generator into a little two-way conversation. A return statement ends the generator with a final value:
function* interview() {
const name = yield "What is your name?";
const lang = yield `Hi ${name}! Favourite language?`;
return `${name} likes ${lang}.`;
}
const chat = interview();
console.log(chat.next().value); // runs to the first yield
console.log(chat.next("Rafa").value); // "Rafa" becomes the value of the first yield
console.log(chat.next("JavaScript")); // finishes with the return valueWhat is your name?
Hi Rafa! Favourite language?
{ value: 'Rafa likes JavaScript.', done: true }
Note that for…of and spread ignore the return value — they stop as soon as done is true.
Delegating with yield*
yield* hands over to another iterable and yields all of its values. It's great for recursive structures like trees:
const tree = {
name: "src",
children: [
{ name: "main.js" },
{ name: "lib", children: [{ name: "math.js" }, { name: "dom.js" }] },
{ name: "style.css" },
],
};
function* walk(node, depth = 0) {
yield " ".repeat(depth) + node.name;
for (const child of node.children ?? []) {
yield* walk(child, depth + 1);
}
}
for (const line of walk(tree)) console.log(line);src
main.js
lib
math.js
dom.js
style.css
Generator methods
| Method | Effect |
|---|---|
gen.next(value) |
resume; value becomes the result of the paused yield |
gen.return(value) |
finish immediately (runs finally blocks) |
gen.throw(error) |
throw an error at the paused yield |
There are also async generators (async function*), which can await inside and are consumed with for await…of — useful for streams of data such as paginated API results.
Test yourself
What does calling a generator function return?
- Its first yielded value
- An array of all values
- A generator object (iterator)
- undefined
What does [...(function* () { yield 1; yield 2; return 3; })()] produce?
- [1, 2, 3]
- [1, 2]
- [3]
- []
What does yield* do?
- Yields every value from another iterable
- Yields a value twice
- Ends the generator
- Multiplies the yielded value