Patterns & principles · 7 of 10 · 16 min read
The Iterator pattern
Walking a collection without knowing how it stores things — a pattern JavaScript built into the language as a protocol.
- Design patterns
Iterator is the pattern for walking a collection one element at a time without exposing how the collection is stored. An array, a linked list and a database cursor all look the same to the code consuming them.
The two protocols
const iterable = {
[Symbol.iterator]() { // the iterable protocol: returns an iterator
let n = 0;
return {
next() { // the iterator protocol: returns { value, done }
return n < 3 ? { value: n++, done: false } : { value: undefined, done: true };
},
};
},
};
console.log([...iterable]); // [0, 1, 2]
for (const n of iterable) console.log(n); // 0 / 1 / 2
Driving it by hand, which is what for...of does for you:
const it = iterable[Symbol.iterator]();
console.log(it.next()); // { value: 0, done: false }
console.log(it.next()); // { value: 1, done: false }
console.log(it.next()); // { value: 2, done: false }
console.log(it.next()); // { value: undefined, done: true }
| Protocol | Requires | Who provides it |
|---|---|---|
| iterable | [Symbol.iterator]() returning an iterator |
the collection |
| iterator | next() returning { value, done } |
the walker |
| both at once | an iterator that returns itself from [Symbol.iterator] |
generators, and most built-ins |
That last row matters: an iterator that is also iterable can be used in for...of directly, which
is why generator objects just work.
Making your own type iterable
A linked list has no indexes, so the consumer must not need them:
class LinkedList {
#head = null;
add(value) {
const node = { value, next: null };
if (!this.#head) {
this.#head = node;
} else {
let cursor = this.#head;
while (cursor.next) cursor = cursor.next;
cursor.next = node;
}
return this;
}
*[Symbol.iterator]() { // a generator method — the shortest correct iterator
let cursor = this.#head;
while (cursor) {
yield cursor.value;
cursor = cursor.next;
}
}
}
const list = new LinkedList().add('a').add('b').add('c');
console.log([...list]); // ["a", "b", "c"]
for (const v of list) console.log(v); // a / b / c
const [first, ...rest] = list;
console.log(first, rest); // "a" ["b", "c"]
console.log(Array.from(list, (v) => v.toUpperCase())); // ["A", "B", "C"]
console.log(Math.max(...new LinkedList().add(1).add(9))); // 9
One method, and five language features started working. That is the payoff of a protocol over a pattern you implement by hand in each class.
Generators write the iterator for you
function* returns an object that is both an iterator and an iterable, and remembers where it left
off between calls:
function* take(n) {
for (let i = 0; i < n; i++) yield i;
}
const gen = take(3);
console.log(gen.next()); // { value: 0, done: false }
console.log([...gen]); // [1, 2] — it resumed, it did not restart
console.log(gen[Symbol.iterator]() === gen); // true — an iterator that is iterable
Note the second line: a generator object is consumed once. Spreading it twice gives you the rest, then nothing. Collections return a fresh iterator each time, which is the difference:
const arr = [1, 2, 3];
console.log([...arr], [...arr]); // [1,2,3] [1,2,3] — a new iterator per spread
const g = take(3);
console.log([...g], [...g]); // [0,1,2] [] — the same exhausted iterator
yield* delegates to another iterable, which makes recursive walks short:
function* walk(node) {
yield node.value;
for (const child of node.children ?? []) yield* walk(child);
}
const tree = { value: 1, children: [{ value: 2, children: [{ value: 3 }] }] };
console.log([...walk(tree)]); // [1, 2, 3]
Laziness is the real advantage
An iterator produces values on demand, so it can describe sequences that are huge, or infinite, or expensive — and the consumer decides how much to pull:
function* naturals() {
let n = 1;
while (true) yield n++; // never ends, and never hangs
}
function* map(iterable, fn) {
for (const value of iterable) yield fn(value);
}
function* takeWhile(iterable, predicate) {
for (const value of iterable) {
if (!predicate(value)) return;
yield value;
}
}
console.log([...takeWhile(map(naturals(), (n) => n * n), (n) => n < 50)]);
// [1, 4, 9, 16, 25, 36, 49] — seven values computed, not a million
The equivalent with arrays would have to build every intermediate collection first, which for an infinite source never finishes. Breaking out early also stops the producer immediately:
for (const n of naturals()) {
if (n > 3) break; // the generator is suspended and then closed
console.log(n); // 1 / 2 / 3
}
break calls the iterator’s return() if it has one — which is how you release a file handle or a
database cursor:
function readRows() {
let open = true;
return {
[Symbol.iterator]() { return this; },
next: () => (open ? { value: 'row', done: false } : { value: undefined, done: true }),
return() { // called on break, throw, or early destructuring
open = false;
console.log('cursor closed');
return { done: true };
},
};
}
for (const row of readRows()) break; // "cursor closed"
A generator gets this for free: its finally block runs when the loop exits early.
Async iteration
The same pattern over values that arrive later, with Symbol.asyncIterator and for await:
async function* pages(firstUrl) {
let url = firstUrl;
while (url) {
const page = await fetch(url).then((r) => r.json());
yield* page.items; // hand out this page's items one by one
url = page.next; // then go and get the next page
}
}
// The consumer never learns that pagination exists:
// for await (const item of pages('/api/items')) console.log(item);
What is already iterable
console.log([...'hi']); // ["h", "i"] — strings, by code point
console.log([...new Set([1, 1, 2])]); // [1, 2]
console.log([...new Map([['a', 1]])]); // [["a", 1]]
console.log([...[1, 2].entries()]); // [[0, 1], [1, 2]]
console.log(typeof [][Symbol.iterator]); // "function"
console.log({}[Symbol.iterator]); // undefined — plain objects are NOT iterable
That last line is the one that catches people: an object is not iterable, which is why
for...of over {} throws and Object.entries() exists.
// for (const x of { a: 1 }) {} // TypeError: {} is not iterable
for (const [k, v] of Object.entries({ a: 1 })) console.log(k, v); // a 1
Common mistakes
Returning a shared iterator from [Symbol.iterator]
Mistake. Storing one iterator on the instance and returning it every time.
Why it fails. The second for...of starts where the first stopped, so the collection appears
empty after one pass.
What to do instead. Return a fresh iterator per call — which a generator method does
automatically.
class Broken {
#it = [1, 2][Symbol.iterator]();
[Symbol.iterator]() { return this.#it; }
}
const b = new Broken();
console.log([...b], [...b]); // [1,2] [] — the second pass found it exhausted
for...of on a plain object
Mistake. Expecting it to walk the properties.
Why it fails. Objects have no [Symbol.iterator], so it is a TypeError. for...in walks
keys — including inherited ones — which is a different thing again.
What to do instead. Object.entries(obj), Object.keys(obj) or Object.values(obj).
Spreading an infinite generator
Mistake. [...naturals()].
Why it fails. The spread pulls until done, which never comes: the tab freezes and then runs
out of memory.
What to do instead. Bound it first — take, takeWhile, or a break in the loop.
Check yourself
One question from the bank on what you just read. Answering here does not affect your quiz history.
In modern JavaScript, what implements the Iterator pattern for you?
Further reading
Everything above is meant to be enough on its own. These are for when you want the full specification of a detail.
Reaching the end of a lecture marks it as read.