Iterators and generators
Overview
Arrays, strings, Maps and Sets all work with for…of and spread because they are iterable: they can hand out their values one at a time through an iterator.
const it = ['a', 'b'][Symbol.iterator]();
it.next(); // { value: 'a', done: false }
it.next(); // { value: 'b', done: false }
it.next(); // { value: undefined, done: true }for…of simply calls next() until done is true.
The iteration protocol
Two small rules make this work:
- An iterable is an object with a method under the key
Symbol.iteratorthat returns an iterator. - An iterator is an object with a
next()method that returns{ value, done }.
Everything that “consumes” iterables relies on these rules: for…of, spread ([...x]), destructuring (const [a, b] = x), Array.from(x), new Set(x), new Map(x), Promise.all(x) and more. Make your object iterable and it works with all of them.
An iterator by hand
const countdown = {
from: 3,
[Symbol.iterator]() {
let current = this.from;
return {
next() {
return current > 0
? { value: current--, done: false }
: { value: undefined, done: true };
},
};
},
};
[...countdown]; // [3, 2, 1]It works, but it’s fiddly. Generators make this far simpler.
Generators
Writing iterators by hand is fiddly. A generator function, marked with *, does it for you. Each yield hands out a value and pauses the function until the next one is requested.
function* steps() {
yield 'Read';
yield 'Try';
yield 'Practise';
}
for (const step of steps()) {
console.log(step);
}Calling steps() doesn’t run any of its code yet. It returns a generator object, which is both an iterator and an iterable. Each next() runs the function until the next yield, then freezes it — local variables and all — until the next request.
The countdown from earlier, as a generator:
function* countdown(from) {
for (let i = from; i > 0; i--) yield i;
}
[...countdown(3)]; // [3, 2, 1]Lazy and infinite sequences
Because values are made only when asked for, a generator can describe an endless sequence safely:
function* ids() {
let n = 1;
while (true) yield `topic-${n++}`;
}
const next = ids();
next.next().value; // 'topic-1'
next.next().value; // 'topic-2'while (true) would freeze the page in a normal function. In a generator it’s fine, because the function pauses at every yield. Just don’t spread an infinite generator ([...ids()]) — that asks for every value.
Laziness is also efficient: you can chain steps without building big arrays in between. Using range and take from this topic’s exercise:
function* filter(iterable, test) {
for (const x of iterable) if (test(x)) yield x;
}
function* map(iterable, fn) {
for (const x of iterable) yield fn(x);
}
const evensSquared = map(filter(range(0, 1_000_000), (n) => n % 2 === 0), (n) => n * n);
[...take(evensSquared, 3)]; // [0, 4, 16] — only the first few numbers are ever checkedModern browsers also offer iterator helpers built in, such as iterator.map(), .filter(), .take() and .toArray(): ids().take(3).toArray().
yield* and returning
yield* hands over to another iterable, yielding each of its values in turn:
function* allTopics() {
yield* ['Loops', 'Arrays'];
yield* steps();
}
[...allTopics()]; // ['Loops', 'Arrays', 'Read', 'Try', 'Practise']A return inside a generator ends it; the returned value appears with done: true (but for…of ignores it).
Making your own objects iterable
const course = {
topics: ['Loops', 'Arrays'],
*[Symbol.iterator]() {
yield* this.topics;
},
};
[...course]; // ['Loops', 'Arrays']The same works in a class, which is a clean way to let people loop over a collection you’ve built:
class Playlist {
#songs = [];
add(song) { this.#songs.push(song); return this; }
*[Symbol.iterator]() { yield* this.#songs; }
}
for (const song of new Playlist().add('A').add('B')) console.log(song);Async generators
Async generators (
async function*) pair withfor await…ofto stream data such as paginated API results.
async function* allPages(url) {
while (url) {
const res = await fetch(url);
const page = await res.json();
yield* page.items;
url = page.next; // null on the last page
}
}
for await (const item of allPages('/api/items?page=1')) {
render(item); // items appear as each page arrives
}The caller just loops; the generator hides all the paging logic.
A range generator
Write a generator range(start, end, step = 1) that yields numbers from start up to (not including) end. Then write take(iterable, n) that yields only the first n values of any iterable.
function* range(start, end, step = 1) {
// your code here
}
function* take(iterable, n) {
// your code here
}
console.log([...range(0, 10, 3)]); // [0, 3, 6, 9]function* range(start, end, step = 1) {
for (let n = start; n < end; n += step) {
yield n;
}
}
function* take(iterable, n) {
if (n <= 0) return;
for (const value of iterable) {
yield value;
if (--n === 0) return;
}
}Summary
- An iterable is anything
for…ofcan loop over; it provides an iterator viaSymbol.iterator. - An iterator has a
next()method returning{ value, done }. - A generator function (
function*) pauses at eachyieldand resumes on the nextnext(). - Generators produce values lazily — only when asked — so they can describe infinite sequences.
async function*withfor await…ofstreams asynchronous data.