Generators and Iterators in JavaScript The Complete Guide
A complete guide to generators and iterators in JavaScript: the iteration protocol, yield, lazy sequences, helpers, async generators, cleanup and real uses.

Every for...of loop, every spread like [...items], every destructuring pattern with square brackets and every call to Array.from, new Set or Promise.all is using the same hidden mechanism: the iteration protocol. It is a small contract that lets any object say "here is how to walk through my contents one item at a time", and it is why arrays, strings, maps, sets and many other things work with the same syntax. Generators are the language's shortcut for writing such objects. A generator function can pause in the middle, hand a value to its caller, and continue later exactly where it stopped, which makes it a natural way to describe a sequence without building it all in memory first. This guide covers the protocol, how to write an iterator by hand, how generators work step by step, two-way communication, delegation, infinite and lazy sequences, the iterator helper methods that arrived in recent engines, asynchronous iteration, cleanup and the traps. Every example shows its exact output on Node.js 24.
The problem iteration solves
A loop needs to ask three questions of a collection: is there another item, what is it, and when does it end. Arrays answer by index, objects by key, linked lists by following a pointer and a database cursor by calling the server. If each structure demanded its own loop, every consumer of data, the loops, the spread, the destructuring, would have to know about every kind of structure. The iteration protocol fixes that by defining one interface that every producer implements and every consumer uses.
const letters = ["a", "b", "c"];
for (const letter of letters) console.log(letter);
console.log([..."hi"], new Set("aab"), Array.from(new Map([[1, "x"]])));a
b
c
[ 'h', 'i' ] Set(2) { 'a', 'b' } [ [ 1, 'x' ] ]A string, a set and a map all feed the same syntax. The protocol is what they have in common, and the next section shows it in plain code.
Iterables and iterators
Two small contracts make up the protocol, and the names are easy to mix up.
An iterator is an object with a next() method. Each call returns an object with two properties: value, the next item, and done, a boolean that is true when there are no more items. An iterable is an object that has a method under the key Symbol.iterator, and calling that method returns an iterator. Arrays, strings, Map, Set, typed arrays, arguments and the results of many standard methods are iterable.
const iterator = [10, 20][Symbol.iterator]();
console.log(iterator.next());
console.log(iterator.next());
console.log(iterator.next());
console.log(iterator.next());{ value: 10, done: false }
{ value: 20, done: false }
{ value: undefined, done: true }
{ value: undefined, done: true }That is the whole loop, written out by hand. A for...of loop calls [Symbol.iterator]() once, calls next() repeatedly and stops at the first result whose done is true. The final value is ignored by the loop. After done becomes true, a well-behaved iterator keeps answering done: true, as the fourth call shows.
Anything that accepts an iterable follows the same steps, so once an object implements the protocol, it works everywhere.
| Consumer | Example |
|---|---|
| Loop | for (const x of iterable) |
| Spread | [...iterable], fn(...iterable) |
| Destructuring | const [first, second] = iterable |
| Constructors | new Set(iterable), new Map(pairs) |
| Static methods | Array.from(iterable), Object.fromEntries(pairs) |
| Promise combinators | Promise.all(iterable), Promise.race(iterable) |
An object that has only next() is an iterator but not an iterable, and the syntax above will reject it with TypeError: x is not iterable.
Writing an iterator by hand
Making your own class iterable means adding a [Symbol.iterator]() method that returns an iterator. The state of the walk, the current position, lives in the iterator, so that two loops over the same object do not interfere.
class Countdown {
constructor(from) {
this.from = from;
}
[Symbol.iterator]() {
let current = this.from;
return {
next: () =>
current > 0
? { value: current--, done: false }
: { value: undefined, done: true },
};
}
}
const countdown = new Countdown(3);
console.log([...countdown]);
console.log([...countdown]);
console.log(Math.max(...countdown));[ 3, 2, 1 ]
[ 3, 2, 1 ]
3Each spread called [Symbol.iterator]() and got a new iterator with its own current, so the second spread started again from three. That is the difference between an iterable, which can be walked many times, and a one-shot iterator, which is exhausted after one pass. Writing the iterator by hand is simple and long, and the amount of bookkeeping is the reason generators exist.
Generator functions
A generator function is declared with function*. Calling it does not run the body. It returns a generator object, which is an iterator, and the body runs in steps, each step ending at a yield.
function* countdown(from) {
for (let n = from; n > 0; n--) {
yield n;
}
}
console.log([...countdown(3)]);
const generator = countdown(2);
console.log(generator.next(), generator.next(), generator.next());
console.log(typeof generator[Symbol.iterator], generator[Symbol.iterator]() === generator);[ 3, 2, 1 ]
{ value: 2, done: false } { value: 1, done: false } { value: undefined, done: true }
function trueCompare this with the class above: six lines instead of fifteen, and the state, n, is an ordinary local variable that the language keeps alive between pauses. The generator object is both an iterator and an iterable, since its own [Symbol.iterator] returns itself, so it works in a for...of loop directly, and, because it returns itself, it can be walked once only.
What happens step by step
The easiest way to understand a generator is to add logging to the body and watch the order of events.
function* steps() {
console.log("start");
const a = yield 1;
console.log("after first yield, a =", a);
const b = yield 2;
console.log("after second yield, b =", b);
return "finished";
}
const run = steps();
console.log("created");
console.log(run.next("ignored"));
console.log(run.next("A"));
console.log(run.next("B"));
console.log(run.next("C"));created
start
{ value: 1, done: false }
after first yield, a = A
{ value: 2, done: false }
after second yield, b = B
{ value: 'finished', done: true }
{ value: undefined, done: true }Calling steps() printed nothing: the body had not started, and the first line shows only created. The first next() ran the body up to the first yield, printed start and paused, handing out 1. The second next("A") resumed, and the expression yield 1 evaluated to "A", which was assigned to a. The first call's argument, "ignored", had nowhere to go, since no yield was waiting for it. The return statement ended the generator: its value came out as the last value with done: true. After that, every call gives { value: undefined, done: true }.
Three rules follow from the trace. The body does not run until the first next(). A yield pauses and produces a value, and when the generator resumes, yield becomes the value passed to next. And a return value is delivered once, in the result with done: true, which for...of and the spread syntax ignore.
function* withReturn() {
yield "a";
yield "b";
return "ignored by loops";
}
console.log([...withReturn()]);
const manual = withReturn();
manual.next();
manual.next();
console.log(manual.next());[ 'a', 'b' ]
{ value: 'ignored by loops', done: true }Lazy sequences
A generator produces values on demand. The code between two yields runs only when the consumer asks for the next value, and not before. That makes it possible to describe sequences that are very large, or never end, without allocating them.
function* naturals() {
let n = 1;
while (true) {
yield n++;
}
}
function* take(iterable, limit) {
let count = 0;
if (limit <= 0) return;
for (const item of iterable) {
yield item;
if (++count >= limit) return;
}
}
console.log([...take(naturals(), 5)]);[ 1, 2, 3, 4, 5 ]naturals has an infinite loop, and the program still finishes, because take stops asking after five items. A function that returned an array could never do this. The infinite generator is safe to write as long as every consumer is bounded, and unsafe to spread: [...naturals()] runs until memory runs out.
Laziness also saves work. A pipeline of generators processes one item at a time through all the steps, and never builds an intermediate array.
function* map(iterable, fn) {
for (const item of iterable) yield fn(item);
}
function* filter(iterable, test) {
for (const item of iterable) if (test(item)) yield item;
}
const result = take(
filter(
map(naturals(), (n) => n * n),
(n) => n % 2 === 1,
),
4,
);
console.log([...result]);[ 1, 9, 25, 49 ]The pipeline squares each natural number, keeps the odd squares and stops after four. Each number travels through map, filter and take before the next one is produced, so no step needs to know how long the sequence is. The same pipeline with arrays would require an upper bound chosen in advance.
Delegating with yield star
yield* hands control to another iterable and produces all of its values, then continues. It is the tool for composing generators and for recursion.
function* inner() {
yield "a";
yield "b";
return "inner done";
}
function* outer() {
yield 1;
const result = yield* inner();
yield result;
yield* [10, 20];
}
console.log([...outer()]);[ 1, 'a', 'b', 'inner done', 10, 20 ]yield* inner() produced "a" and "b", and the whole expression evaluated to the return value of inner, "inner done", which the next line yielded. yield* also accepts any iterable, so yield* [10, 20] works. Delegation is what makes recursive generators short.
function* walk(tree) {
yield tree.name;
for (const child of tree.children ?? []) {
yield* walk(child);
}
}
const folder = {
name: "root",
children: [
{ name: "src", children: [{ name: "index.js" }, { name: "util.js" }] },
{ name: "README.md" },
],
};
console.log([...walk(folder)]);[ 'root', 'src', 'index.js', 'util.js', 'README.md' ]The generator visits the tree depth first and produces names one at a time. The consumer can stop early, and the traversal stops with it, so a search for the first match does not walk the rest of the tree.
function find(tree, name) {
for (const entry of walk(tree)) {
if (entry === name) return true;
}
return false;
}
console.log(find(folder, "src"), find(folder, "missing"));true falseSending values into a generator
The argument of next becomes the result of the paused yield expression, so a generator can receive data as well as produce it. That turns it into a small coroutine, a function that you drive from outside.
function* averager() {
let sum = 0;
let count = 0;
let average;
while (true) {
const number = yield average;
sum += number;
count += 1;
average = sum / count;
}
}
const running = averager();
running.next();
console.log(running.next(10).value, running.next(20).value, running.next(60).value);10 15 30The first next() call only starts the generator and runs it to the first yield, so its argument would be lost. After that, each next(value) delivers a number, and the generator replies with the updated average. The state, sum and count, is local to the generator and invisible from outside. Two-way generators are rare in application code, and they are the idea behind the older libraries that wrote asynchronous code as generators before async and await existed: the driver passed each resolved promise value back in through next.
Errors, return and cleanup
A consumer can end a generator in two other ways: by throwing an error into it with throw(), or by closing it early with return(). The generator can handle both with try, catch and finally.
function* guarded() {
try {
yield 1;
yield 2;
} catch (error) {
console.log("caught", error.message);
yield "recovered";
} finally {
console.log("cleanup");
}
}
const generator = guarded();
console.log(generator.next());
console.log(generator.throw(new Error("boom")));
console.log(generator.next());{ value: 1, done: false }
caught boom
{ value: 'recovered', done: false }
cleanup
{ value: undefined, done: true }throw(error) resumes the generator by raising the error at the paused yield, where the generator's own catch handled it and yielded a value. The finally block ran when the generator ended. return(value) also resumes the generator, but ends it at once, running any finally blocks on the way out.
function* resource() {
try {
yield 1;
yield 2;
yield 3;
} finally {
console.log("closed");
}
}
for (const n of resource()) {
console.log(n);
if (n === 2) break;
}
const early = resource();
early.next();
console.log(early.return("stopped"));1
2
closed
closed
{ value: 'stopped', done: true }Leaving a for...of loop early, with break, return or a thrown error, calls return() on the iterator, so the finally block runs and the resource is released. The same happens for destructuring that stops early. That is the reason to put cleanup in finally inside a generator: it works however the consumer stops. Writing an iterator by hand, you provide the same hook by adding a return() method.
Iterator helper methods
Iterators used to have only next, and every transformation had to be a generator function that you wrote or a library you installed. Recent engines add methods directly on iterators: map, filter, take, drop, flatMap, reduce, toArray, forEach, some, every and find, plus Iterator.from to wrap anything iterable. They are in Node.js 22 and later, and in current browsers.
function* naturals() {
let n = 1;
while (true) yield n++;
}
console.log(naturals().filter((n) => n % 2 === 0).map((n) => n * n).take(3).toArray());
console.log(naturals().drop(2).take(3).toArray());
console.log(naturals().find((n) => n > 3), naturals().some((n) => n > 100));
console.log(Iterator.from([1, 2, 3]).map((n) => n * 2).toArray());
console.log([1, 2, 3].values().reduce((sum, n) => sum + n, 0));
console.log([[1, 2], [3]].values().flatMap((part) => part).toArray());[ 4, 16, 36 ]
[ 3, 4, 5 ]
4 true
[ 2, 4, 6 ]
6
[ 1, 2, 3 ]The helpers are lazy like the generator pipeline above, and they stop early: find and some stop at the first answer, even on an infinite iterator. They live on iterators, not on arrays, so convert an array with .values() first, and finish with toArray() when you need an array back. They replace the hand-written map, filter and take generators in most code, and generators remain the tool for new sources and for logic that needs several yields.
Generators as state machines
A generator remembers where it was, which makes it a compact way to write a state machine: code that moves through a sequence of states in order.
function* trafficLight() {
while (true) {
yield "green";
yield "yellow";
yield "red";
}
}
const light = trafficLight();
console.log(light.next().value, light.next().value, light.next().value, light.next().value);green yellow red greenThe loop is the whole cycle, and no state variable needs to be stored and updated by hand. The same shape suits a wizard with steps, a retry sequence with growing delays, a parser that moves through phases and a game script that waits for input at each step.
function* backoff(base, max) {
let delay = base;
while (true) {
yield delay;
delay = Math.min(delay * 2, max);
}
}
console.log(backoff(100, 1000).take(6).toArray());[ 100, 200, 400, 800, 1000, 1000 ]A generator of delays is easy to test and to reuse, since the retry loop just asks for the next one.
Practical generators
A few small generators earn their place in real code.
function* chunk(iterable, size) {
let batch = [];
for (const item of iterable) {
batch.push(item);
if (batch.length === size) {
yield batch;
batch = [];
}
}
if (batch.length > 0) yield batch;
}
function* lines(text) {
let start = 0;
for (let i = 0; i < text.length; i++) {
if (text[i] === "\n") {
yield text.slice(start, i);
start = i + 1;
}
}
if (start < text.length) yield text.slice(start);
}
function* pairs(object) {
for (const key of Object.keys(object)) yield [key, object[key]];
}
console.log([...chunk([1, 2, 3, 4, 5], 2)]);
console.log([...lines("alpha\nbeta\ngamma")]);
console.log(new Map(pairs({ a: 1, b: 2 })));[ [ 1, 2 ], [ 3, 4 ], [ 5 ] ]
[ 'alpha', 'beta', 'gamma' ]
Map(2) { 'a' => 1, 'b' => 2 }chunk batches any iterable, which is useful for sending records to an API in groups. lines walks a large string without splitting it into one big array. pairs shows that a generator can feed any consumer of an iterable, here the Map constructor. Because generators are lazy, chunk can sit in front of a database cursor and fetch only as many rows as the consumer has asked for.
Asynchronous iteration
Some sequences arrive over time: pages from an API, lines from a stream, events from a socket. For those, JavaScript has async iterators. An async iterable has a method under Symbol.asyncIterator that returns an object whose next() returns a promise, and for await...of consumes it. An async generator, written async function*, is the easy way to produce one.
async function* pages() {
for (let page = 1; page <= 3; page++) {
await new Promise((resolve) => setTimeout(resolve, 5));
yield { page, items: [page * 10, page * 10 + 1] };
}
}
for await (const { page, items } of pages()) {
console.log(page, items);
}1 [ 10, 11 ]
2 [ 20, 21 ]
3 [ 30, 31 ]The loop waits for each page before asking for the next, so the producer and the consumer move in step. This gives natural back-pressure: a slow consumer slows the producer, and the producer never gets far ahead. for await is sequential by design. If you want to process pages in parallel, collect them first, with Array.fromAsync, and then use Promise.all.
import { Readable } from "node:stream";
const collected = await Array.fromAsync(pages());
console.log(collected.length);
for await (const chunk of Readable.from(["a", "b"])) {
console.log("chunk", chunk);
}3
chunk a
chunk bNode.js streams are async iterables, so for await is the simple way to read a file or an HTTP body in chunks, and Readable.from turns any iterable or async iterable into a stream. Errors work like they do elsewhere: an error thrown in an async generator rejects the pending next() promise, and for await rethrows it, where a try and catch can handle it. Leaving the loop early calls return(), so the generator's finally block runs, and a stream is destroyed.
async function* paginate(fetchPage) {
let cursor = null;
do {
const { items, next } = await fetchPage(cursor);
yield* items;
cursor = next;
} while (cursor !== null);
}
const fakeApi = async (cursor) =>
cursor === null ? { items: ["a", "b"], next: 2 } : { items: ["c"], next: null };
const all = [];
for await (const item of paginate(fakeApi)) all.push(item);
console.log(all);[ 'a', 'b', 'c' ]This is the cleanest answer to "loop over every page of an API". The consumer sees one flat sequence of items, and the cursor logic stays inside the generator. yield* inside an async generator delegates to a sync iterable, here the array of items.
How generators relate to other tools
Generators sit between several things you already know. Compared with an array, a generator holds one item at a time and can be infinite, but it can be consumed once, has no length and does not support random access. Compared with a callback or an event emitter, a generator lets the consumer decide when to ask for the next item, which is pull instead of push. Compared with a stream, an async generator is simpler to write and read, and a stream has more controls for buffering and piping. Compared with async and await, which are built on the same pause and resume machinery, a generator can produce many values over its life, and an async function produces one.
| You need | Use |
|---|---|
| A small list with random access | an array |
| A sequence produced on demand, possibly infinite | a generator |
| A sequence that arrives over time | an async generator or a stream |
| Many listeners reacting to events | an event emitter |
| One value from asynchronous work | an async function |
Iterables you already use
Before you write your own, it helps to know how many standard values are iterable, because most of the time the right move is to use one of them. Arrays, strings, typed arrays, Map, Set, the arguments object, DOM collections such as NodeList, and the results of methods like matchAll, Object.entries and Array.prototype.entries all take part in the protocol. Each defines what one step means, and the details are worth learning because they decide what a loop gives you.
| Value | What one step produces |
|---|---|
| Array | the next element, in index order, including holes as undefined |
| String | the next code point, so an emoji is one step and not two |
Map | a [key, value] pair, in insertion order |
Set | the next value, in insertion order |
array.entries() | an [index, value] pair |
object | nothing, since plain objects are not iterable |
string.matchAll(regex) | the next match object, with its groups and position |
Strings deserve a note, since the iteration is by code point, which differs from the index-based length and charAt. A loop over a string that contains an emoji visits the emoji once, and a loop with an index visits its two halves separately. Maps and sets iterate in the order in which items were added, which the language guarantees, and which is why a Set is the standard way to remove duplicates while keeping the first occurrence.
Plain objects are the exception that surprises people. They are not iterable, so for...of throws on them, and you convert them first with Object.keys, Object.values or Object.entries, each of which returns an array. If you want an object that works with for...of, give its class a [Symbol.iterator] method, as the examples above do.
The protocol in detail
The two contracts have a few details that the short version leaves out, and they matter when you write an iterator by hand or debug one that misbehaves.
The result object returned by next() must have done and value, and either may be omitted: a missing done counts as false, and a missing value as undefined. When done is true, value carries the return value of the sequence, which loops ignore. Once an iterator has reported done: true, it is expected to keep doing so, though the language does not enforce it.
An iterator may also have a return() method and a throw() method, both optional. return() is called by the language when a consumer stops early, which happens when a for...of loop is left through break, return or an exception, and when a destructuring pattern takes fewer items than the iterator holds. Its job is cleanup: close a file, release a lock, cancel a request. throw() is called only by code that drives the iterator by hand, and yield* forwards it. If an iterator has no return(), early exit just abandons it, which is fine for an in-memory sequence and a leak for one that holds a resource.
const tracked = {
[Symbol.iterator]() {
let n = 0;
return {
next: () => ({ value: ++n, done: false }),
return() {
console.log("return called");
return { done: true };
},
};
},
};
const [first, second] = tracked;
console.log(first, second);
for (const n of tracked) {
if (n === 3) break;
}return called
1 2
return calledBoth the destructuring and the break called return(), since each took fewer items than the infinite iterator could give. Libraries that wrap file handles, database cursors and network streams as iterators rely on this hook to release the resource, and a hand-written iterator for such a source needs it too.
Another subtle point is that an object can be an iterable and an iterator at once, by returning this from [Symbol.iterator]. Generator objects do exactly that, and so do the iterators of arrays. The consequence is that you can pass the same object to a consumer twice, and the second consumer continues where the first stopped. Sometimes that is what you want, as when you read a header from a stream and then loop over the rest, and sometimes it is a bug.
How a generator pauses
It is useful to have a picture of what the engine does, even though you never see it. When you call a generator function, the engine allocates the generator object and, with it, a saved copy of the function's local state: its variables and the position in its code. Nothing runs yet. A call to next() restores that state, runs until the next yield, saves the state again and returns the yielded value to the caller. The state is stored on the heap, not on the call stack, which is why a generator can be paused for as long as you like without holding any stack space, and why it works like a closure over its own locals.
This also explains why a generator is not parallel. Only one piece of code runs at any moment, and a generator never runs in the background. It runs when its consumer calls next(), and the consumer waits until the generator yields or finishes. A generator in the middle of a for...of loop is a conversation between two pieces of code that take turns. The turn-taking is cheap, and it is exactly the property that makes lazy pipelines work, since each stage runs just long enough to produce one item for the next.
A data pipeline from generators
Real work is usually a pipeline: read, parse, filter, transform, batch and write. With generators, each stage is a small function that takes an iterable and returns an iterable, and the stages connect by composition. The advantage over a chain of array methods is that nothing is held in memory beyond one item, and the first results appear before the last input is read.
function* parseRecords(lines) {
for (const line of lines) {
const [id, name, score] = line.split(",");
yield { id: Number(id), name, score: Number(score) };
}
}
function* onlyPassing(records, minimum) {
for (const record of records) {
if (record.score >= minimum) yield record;
}
}
function* batches(items, size) {
let batch = [];
for (const item of items) {
batch.push(item);
if (batch.length === size) {
yield batch;
batch = [];
}
}
if (batch.length > 0) yield batch;
}
const input = ["1,Ana,91", "2,Bo,48", "3,Cy,77", "4,Di,60", "5,Ed,95"];
for (const batch of batches(onlyPassing(parseRecords(input), 60), 2)) {
console.log(batch.map((record) => record.name));
}[ 'Ana', 'Cy' ]
[ 'Di', 'Ed' ]Each stage knows nothing about the others. parseRecords could read from a file, onlyPassing could be replaced with any test and batches could feed a bulk insert. To swap the source for a real file, replace the input array with an async generator that reads lines from a stream, and change the loops to for await. The structure of the program does not change, which is the real benefit: the sequence logic is separated from the source of the data and from its destination.
When you design such a pipeline, give each stage a name that says what it does to the stream, make each stage a pure function of its input where possible, and keep the side effects, such as writing, in the final loop. A stage that does I/O in the middle of a pipeline makes the order of events harder to follow, because a lazy pipeline interleaves its stages, and the effects happen item by item, not stage by stage.
Designing APIs that return iterables
When a function returns a collection, you choose between returning an array and returning an iterable. An array is simple, supports length and random access, and can be read many times, and it costs memory for every item and requires the producer to finish before the consumer starts. An iterable can start delivering at once, uses little memory and can be infinite, but it can usually be read only once, has no length and cannot be indexed. Return an array when the data is small and bounded. Return an iterable, usually from a generator, when the data is large, expensive to produce or open-ended, and say in the documentation whether the result can be read more than once.
If you return a generator object, callers who loop twice will get nothing the second time and no error. If you return an object whose [Symbol.iterator] creates a fresh generator on each call, as the Range class above does, the loop works as many times as callers like, and the type behaves like a collection. That second form is the friendlier API. Name functions that return iterables for what they produce, such as walk, lines or entries, and avoid names that suggest an array, such as getItems. When callers will want an array, they can spread the result, and you save them nothing by doing it for them.
Typing generators in TypeScript
TypeScript describes a generator with Generator<T, TReturn, TNext>: the type of the yielded values, the type of the returned value and the type that next accepts. For most generators, only the first matters.
function* countdown(from: number): Generator<number, string, void> {
for (let n = from; n > 0; n--) yield n;
return "liftoff";
}
function* accumulator(): Generator<number, void, number> {
let total = 0;
while (true) {
const addition: number = yield total;
total += addition;
}
}
const sums = accumulator();
sums.next();
console.log([...countdown(2)], sums.next(5).value, sums.next(7).value);[ 2, 1 ] 5 12The Generator<number, string, void> says that countdown yields numbers, returns a string and takes nothing from next. In accumulator, the third parameter is number, so the compiler checks that next is called with a number. A function that only needs to say it returns something iterable can use Iterable<T> or IterableIterator<T> as its return type, which is simpler and hides the generator machinery. For async generators the types are AsyncGenerator and AsyncIterable. The downlevelIteration compiler option, or a target of ES2015 and later, is needed for iterables other than arrays in compiled spread and for...of.
Testing and debugging generators
A generator is easy to test because it is a function that returns values. Collect a bounded number of items with take or toArray and compare them with an array of expected values. For an infinite generator, always bound the test, or it never ends. To test two-way behavior, call next with the values you want and assert on each result.
import { test } from "node:test";
import assert from "node:assert/strict";
function* fizz(limit) {
for (let n = 1; n <= limit; n++) {
yield n % 15 === 0 ? "FizzBuzz" : n % 5 === 0 ? "Buzz" : n % 3 === 0 ? "Fizz" : n;
}
}
test("fizz yields the right sequence", () => {
assert.deepEqual([...fizz(5)], [1, 2, "Fizz", 4, "Buzz"]);
});
test("early exit runs cleanup", () => {
let closed = false;
function* source() {
try {
yield 1;
yield 2;
} finally {
closed = true;
}
}
for (const item of source()) {
if (item === 1) break;
}
assert.equal(closed, true);
});ā fizz yields the right sequence (0.8ms)
ā early exit runs cleanup (0.3ms)The second test checks the property that is easiest to break: that stopping a loop early releases what the generator holds. To debug a generator, set a breakpoint inside it, and the debugger will stop each time it resumes. Logging at the top of the body shows when it starts, which is at the first next and not at the call, a fact that explains many reports of "my generator does not run". If a pipeline misbehaves, insert a pass-through generator that logs each item it sees, and put it between the stages to see where the data changes.
Moving loops and callbacks to generators
A good candidate for conversion is a function that takes a callback and calls it for each item, such as walk(tree, visit). The callback style cannot stop early without a special return value and cannot be composed. The generator version, walk(tree), can be used in for...of, stopped with break, passed to take and combined with other sequences. The conversion is mechanical: replace each visit(item) call with yield item, and the function becomes the sequence.
Another candidate is code that builds a big array only to loop over it once, as in const rows = loadAll(); for (const row of rows) .... If loadAll can produce one row at a time, make it a generator, and the loop body does not change at all. Memory use falls from the size of the result to the size of one row. The cases to leave alone are the ones where the array is needed in full, for sorting, grouping or counting, since a generator would have to be collected into an array at once.
The family tree: generators and async functions
Generators are the older sibling of async and await, and seeing the relationship clears up both. Before async functions existed, libraries ran asynchronous code by writing it as a generator that yielded promises. A small driver function called next, waited for each yielded promise to settle and passed the resolved value back in through the next next(value) call, or threw the rejection into the generator with throw. The generator body read as straight-line code, and the driver handled the waiting. The async function is the same idea built into the language: await plays the part of yield, and the engine plays the driver.
function run(generatorFunction) {
const generator = generatorFunction();
function step(input) {
const { value, done } = generator.next(input);
if (done) return Promise.resolve(value);
return Promise.resolve(value).then(step);
}
return step();
}
const delay = (ms, value) => new Promise((resolve) => setTimeout(() => resolve(value), ms));
const result = await run(function* () {
const first = yield delay(5, 10);
const second = yield delay(5, 20);
return first + second;
});
console.log(result);30The driver is eleven lines, and it runs the generator as if it were an async function: each yield waits for a promise and resumes with its value. This sketch leaves out error handling, which a full driver does with throw. You will not write code like this today, and knowing it exists explains why the two features share their machinery, why an async function cannot be an arrow generator and why an async generator, which combines await and yield, is possible at all.
Deep trees and the call stack
A recursive generator uses yield* to visit nested data, and each level of nesting adds a generator object that sits between the consumer and the item. For ordinary data, such as a file tree or a parsed document, the depth is small and nothing needs attention. For very deep structures, such as a linked list of a hundred thousand nodes, a recursive yield* can run out of stack, and the cost of passing each value up through many levels grows with the depth. The alternative is an explicit stack, kept in an array, inside a single generator.
function* depthFirst(root) {
const stack = [root];
while (stack.length > 0) {
const node = stack.pop();
yield node.name;
for (const child of [...(node.children ?? [])].reverse()) stack.push(child);
}
}
const tree = {
name: "root",
children: [{ name: "a", children: [{ name: "a1" }] }, { name: "b" }],
};
console.log([...depthFirst(tree)]);[ 'root', 'a', 'a1', 'b' ]The order is the same as the recursive version, and the depth no longer matters, since the stack lives on the heap. Reversing the children before pushing keeps the left to right order, because a stack gives items back in the opposite order. Use the recursive version when the structure is shallow and clarity matters, and the explicit stack when the input is untrusted or very deep.
Iterators in the browser and in Node.js
Many platform APIs return iterators, and recognizing them saves conversions. In the browser, document.querySelectorAll returns a NodeList that is iterable, FormData and URLSearchParams have entries, keys and values iterators, and Headers can be spread into pairs. Collections returned by getElementsByClassName are iterable in current browsers, and Array.from converts any of them to an array when you need map and filter. In Node.js, fs.opendir returns an async iterable of directory entries, readline.createInterface gives an async iterable of lines, streams are async iterable, and events.on(emitter, "name") turns an event emitter into an async iterator of event arguments. Each of these removes callback code: where an older API needed three event handlers, you write one for await loop and a try.
const params = new URLSearchParams("a=1&b=2&a=3");
console.log([...params], Object.fromEntries(params));
console.log([...params.keys()], params.getAll("a"));[ [ 'a', '1' ], [ 'b', '2' ], [ 'a', '3' ] ]
{ a: '3', b: '2' }
[ 'a', 'b', 'a' ] [ '1', '3' ]Spreading URLSearchParams gives every pair, including the repeated a. Object.fromEntries keeps only the last value of a repeated key, which is a lossy conversion to be aware of, and getAll returns every value.
Glossary
| Term | Meaning |
|---|---|
| Iterable | an object with a [Symbol.iterator]() method that returns an iterator |
| Iterator | an object with a next() method that returns { value, done } |
| Generator function | a function* that returns a generator object when called |
| Generator object | an iterator and iterable that runs the generator body in steps |
yield | pauses the generator and produces a value, and evaluates to the next input |
yield* | delegates to another iterable and evaluates to its return value |
| Async iterable | an object with [Symbol.asyncIterator]() whose iterator returns promises |
| Async generator | an async function* that can await and yield |
| Exhausted | an iterator that has returned done: true and has nothing more to give |
| Lazy | computed only when asked for, one item at a time |
Gotchas
A generator can be consumed only once. After it is exhausted, it is empty, and a second loop gets nothing, with no error.
function* three() {
yield 1;
yield 2;
yield 3;
}
const sequence = three();
console.log([...sequence], [...sequence]);
console.log([...three()], [...three()]);[ 1, 2, 3 ] []
[ 1, 2, 3 ] [ 1, 2, 3 ]Call the generator function again to get a fresh run, or make the object an iterable whose [Symbol.iterator] is a generator method, so that each loop starts anew.
class Range {
constructor(start, end) {
this.start = start;
this.end = end;
}
*[Symbol.iterator]() {
for (let n = this.start; n < this.end; n++) yield n;
}
}
const range = new Range(1, 4);
console.log([...range], [...range]);[ 1, 2, 3 ] [ 1, 2, 3 ]The *[Symbol.iterator]() form is the shortest way to make a class iterable, and each loop gets its own generator. Other traps are worth knowing. Generators cannot be arrow functions, so there is no short form for an inline generator. The body does not run until the first next(), so an error in the first lines surfaces at the first iteration and not at the call. Spreading an infinite generator never ends. A return value is ignored by for...of and the spread syntax. And yield has a low precedence, so const x = yield a + b yields the sum, and (yield a) + b is the way to add to the result of the yield.
When not to use a generator
If the data is small and you need to loop over it more than once, an array is simpler. If you need length, indexing or sorting, you have to collect the values into an array anyway. If the work is asynchronous but produces one result, an async function is the right tool. And if you only need to transform a list once, a map or filter chain on an array is clear, and the laziness of a generator saves nothing worth the extra concept. We do not claim that generators are faster or slower than other loops: that depends on the engine and the code, and the reason to use them is the shape of the problem, which is a sequence that is large, infinite or produced step by step.
Where this guide stops
Several related topics are outside this guide. Observables, as in RxJS, build push-based streams with operators and are a separate library with a separate mental model. The Streams API in the browser and Node.js has its own pipeline and back-pressure controls. Web Workers and the Atomics API handle real parallelism, which generators do not provide, since a generator interleaves work on a single thread. And for the exact semantics of every edge case, the ECMAScript specification and the MDN pages on the iteration protocols are the reference.


