Lesson 13 of 50JavaScript in depth
Iterators and Generators
Learn the protocol behind for...of, write lazy and infinite sequences with generators, use iterator helpers, and page through APIs with for await.
Your team needs a nightly job that exports every order from an API. The API returns 100 orders per page and there are 40,000 pages. The first version fetches every page into one giant array, then loops over it, and the job dies with an out-of-memory error at page 31,000. What you want is a loop that asks for the next order only when it is ready for it, fetches a page only when the last one runs out, and stops cleanly if someone breaks out early. That is exactly what iterators and generators give you. They are also behind every for...of loop, every spread and every destructuring you have written, so understanding them explains a lot of JavaScript you already use.
The iteration protocol
In Maps and Sets you saw that map.keys() returns an iterator, not an array. Two small contracts sit behind that word.
- An iterable is any object with a method stored under the key
Symbol.iterator. Calling that method returns an iterator. - An iterator is an object with a
next()method. Each call returns a result object{ value, done }. While there are values,doneisfalse. When the sequence is finished,doneistrue.
Arrays, strings, Maps, Sets, arguments, NodeLists and typed arrays are all iterable. You can drive the protocol by hand to see it:
Press Run (⌘ Enter) to see what happens.Every built-in feature that "loops over things" is a consumer of this protocol. for...of, spread ([...x]), array destructuring (const [first] = x), Array.from, new Map(x), new Set(x), Promise.all(x) and yield* all call x[Symbol.iterator]() and then call next() until done is true. That is why you can spread a Set or destructure a string: they speak the same protocol as arrays.
The loop asks the iterable for a fresh iterator. This happens once, before the first pass.
Two details matter. First, destructuring only pulls as many values as it needs: const [a, b] = hugeIterator calls next() twice, then closes the iterator. Second, plain objects are not iterable. for (const x of { a: 1 }) throws TypeError: ... is not iterable. That is a deliberate choice: an object is a record, and it is not obvious whether you would want keys, values or pairs. You choose explicitly with Object.keys, Object.values or Object.entries, which return arrays.
Making your own objects iterable
Any class can join in by defining [Symbol.iterator](). Here is a playlist that hides its storage but still works with for...of and spread:
Press Run (⌘ Enter) to see what happens.Notice that spreading the playlist twice works both times. Each call to [Symbol.iterator]() builds a new iterator with its own i. That is the difference between an iterable and an iterator, and it causes a classic bug: an iterator is one-shot. Once it reports done, it stays done.
const it = new Set([1, 2, 3]).values(); console.log([...it].length, [...it].length);
Writing next() by hand works but is fiddly: you track state in closures and build result objects yourself. Generators remove all of that.
Generators: functions that pause
A generator function is written function*. Calling it does not run its body. It returns a generator object, which is both an iterator and an iterable. Each next() runs the body until the next yield, hands that value out, and pauses right there with all its local variables intact. The next next() resumes from the same spot.
Press Run (⌘ Enter) to see what happens.The log shows the interleaving. created comes first, because calling steps() ran nothing. start only appears inside the first next(). The final next() runs to the end of the function and returns { value: undefined, done: true }. If the function had return 3, the last result would be { value: 3, done: true }, but for...of and spread ignore that returned value, because it arrives with done: true.
What does this print?
function* gen() {
console.log("A");
yield "x";
console.log("B");
yield "y";
return "z";
}
const it = gen();
console.log("C");
const out = [...it];
console.log(out.join(","));With generators, the Playlist's iterator method shrinks to two lines:
*[Symbol.iterator]() {
yield* this.#songs;
}yield* other delegates: it yields every value from another iterable, one at a time, before continuing. It is also how you write recursive generators. A depth-first walk of a nested tree, or a lazy flatten, is a few lines:
Press Run (⌘ Enter) to see what happens.Unlike nested.flat(Infinity), this version never builds the whole flat array, and when the loop breaks at 3 it does no further work.
Lazy and infinite sequences
Because a generator only computes the next value when asked, it can describe a sequence that never ends. Laziness means the consumer decides how much work happens.
Press Run (⌘ Enter) to see what happens.The while (true) loop is safe because each yield pauses it. The danger moves to the consumer: [...idGenerator("ORD")] or Array.from on an infinite generator will hang the tab, because they try to read until done. Always bound an infinite sequence with break, destructuring, or take (shown below).
At work, generators show up as id and cursor sources, test data builders, tokenizers and parsers that produce one token at a time, and tree or graph walkers. Libraries also use them internally. Redux-Saga built its whole model on generators, and many parsers and stream utilities are generator code underneath.
Talking back: next, return and throw
yield is an expression, not only a statement. Whatever you pass to next(value) becomes the result of the paused yield. The first next() call has no paused yield to receive its argument, so that argument is thrown away. This is the answer to the interview question "what does yield return?": it returns whatever the caller sends into the next next() call, or undefined if they send nothing.
Press Run (⌘ Enter) to see what happens.Generators also have return(value), which finishes the generator as if a return statement ran at the paused yield, and throw(error), which makes the paused yield throw. Both run any finally blocks on the way out. That is the important part for real code: when a for...of loop exits early through break, return or an exception, it calls the iterator's return() method. A generator responds by running its finally block, so you can release a file handle, close a connection or log that the consumer stopped.
Press Run (⌘ Enter) to see what happens.What does this print?
function* g() {
try {
yield 1;
yield 2;
} finally {
console.log("cleanup");
}
}
const [first] = g();
console.log(first);A generator that is never finished and never closed simply stays paused until it is garbage collected, and its finally never runs. If cleanup matters, consume it with for...of (which closes it for you) or call return() yourself.
How do generators pause without threads?
A generator does not run on a separate thread. When it hits yield, the engine saves its execution context (local variables, the current position in the code, any try blocks it is inside) into the generator object and returns to the caller. next() restores that context and continues. Everything stays on one thread, in order, which is why the logs above interleave so predictably. async/await is built on the same machinery: before async functions existed, libraries such as co ran generators that yielded promises, resuming them when each promise settled. An async function is essentially that pattern built into the language.
Iterator helpers (ES2025)
For years iterators had no map or filter, so you wrote [...iter].filter(...), which builds a full array first. ES2025 added iterator helpers: methods on every built-in iterator (including generator objects), available in current browsers and Node 22+. The list covers map, filter, take, drop, flatMap, reduce, toArray, forEach, some, every and find. Plus Iterator.from(x) wraps any iterable, or any object with a next() method, so it gets the helpers too.
The key difference from array methods is lazy versus eager. array.map(f).filter(g) runs f on every element, builds a new array, then runs g over all of that. iterator.map(f).filter(g).take(3) builds nothing. Each value flows through the whole chain one at a time, and the pipeline stops as soon as take(3) has its three.
Press Run (⌘ Enter) to see what happens.The array version squares 1,000 numbers. The iterator version squares six. Arrays do not have these helpers directly, so you reach the lazy versions through array.values(). Three cautions. Helpers return iterators, so they are one-shot like any other. There is no lazy sort or reverse, because those need every value first. And for a few hundred items, plain array methods are fine and often clearer. Reach for the lazy chain when the source is large, expensive to produce, or infinite.
For [10, 20, 30].values().map(f).take(1).toArray(), put the calls in the order they happen.
- Tap the steps below in the right order.
Async iterators: paging through APIs
This section and the next lean on promises and TypeScript, which come later in the course. On a first pass, skim them and return after the Async JavaScript and TypeScript units.
Back to the nightly export. Fetching a page is asynchronous, so the plain protocol does not fit: next() would need to return a value it does not have yet. Async iterables solve this. They use Symbol.asyncIterator, and their next() returns a promise of { value, done }. You consume them with for await...of, and the easiest way to write one is an async function*, which can both await and yield.
Press Run (⌘ Enter) to see what happens.The loop fetches a page only when the previous one is used up, holds one page in memory at a time, and stops fetching the moment you break. The calling code reads like a simple loop and knows nothing about cursors. That separation is the main win: the pagination logic lives in one generator, and every report, export or sync job reuses it.
Array.fromAsync (ES2024) collects an async iterable into an array, which is handy in tests and small scripts. Other async iterables you will meet: Node streams (for await (const chunk of fs.createReadStream(path))), readline interfaces for reading a file line by line, and web ReadableStreams, which are async iterable in Node and in Chrome and Firefox (check Can I Use before relying on it in Safari). Note that iterator helpers are sync only in ES2025. Async iterator helpers are still a proposal, so for async sources you write the loop yourself.
Two cautions for production. for await processes one item at a time, which is gentle on the API but slow if each item needs its own request. Combine it with the concurrency limits from Async patterns when you need parallel work. And handle errors inside the generator or around the loop: a rejected fetchPage throws out of for await at the point of the next item.
Typing iterators in TypeScript
TypeScript has types for every piece of the protocol. Accept the loosest one you need: a parameter typed Iterable<T> takes arrays, Sets, Map keys and generators alike. Annotate generators with Generator<Yield, Return, Next> and async ones with AsyncGenerator<Yield, Return, Next>, where Next is the type passed into next().
function* idGenerator(prefix: string): Generator<string, never, void> {
let n = 1;
while (true) yield `${prefix}-${n++}`;
}
function sum(values: Iterable<number>): number {
let total = 0;
for (const v of values) total += v;
return total;
}
sum([1, 2, 3]);
sum(new Set([4, 5]));Match each tool to the job it fits best.
- iterable
- An object with a
[Symbol.iterator]()method that returns a fresh iterator. Arrays, strings, Maps and Sets are iterable. - iterator
- An object whose
next()returns{ value, done }. One-shot: once done, it stays done. - generator
- A
function*that returns an iterator and pauses at eachyielduntil the nextnext()call. - lazy evaluation
- Computing each value only when a consumer asks for it, so unused values cost nothing.
- iterator helpers
- ES2025 methods such as
map,filterandtakeon iterators. Lazy, unlike the array versions. - async iterable
- An object with
[Symbol.asyncIterator]()whosenext()returns a promise. Consumed withfor await...of.