Sub topic 7
Making Objects Iterable with Symbol.iterator
This chapter assumes you know ES6 classes, for...of loops, spread syntax, and the idea from the previous chapter that well-known symbols are hooks the language looks up on your objects. It also helps to have seen generator functions (function*), but they are explained briefly here.
The Iteration Protocol
Arrays, strings, Maps, and Sets work with for...of because each has a method stored under the key Symbol.iterator. A plain object has no such method, so iterating it fails:
const point = { x: 1, y: 2 };
try {
for (const v of point) console.log(v);
} catch (e) {
console.log(e.message); // "point is not iterable" (wording varies by engine)
}The protocol has two parts:
- An iterable is any object with a
[Symbol.iterator]()method that returns an iterator. - An iterator is an object with a
next()method. Each call returns{ value, done }. Whendoneistrue, iteration stops.
Writing an Iterator by Hand
Implementing the protocol directly shows exactly what the loop expects:
class Countdown {
constructor(from) {
this.from = from;
}
[Symbol.iterator]() {
let current = this.from;
return {
next() {
if (current < 0) return { value: undefined, done: true };
return { value: current--, done: false };
}
};
}
}
console.log([...new Countdown(3)]); // [3, 2, 1, 0]The iteration state (current) lives inside the iterator, not on the Countdown instance. Each call to [Symbol.iterator]() starts a fresh, independent pass, so you can loop over the same object twice.
The Generator Shortcut
A generator function returns an object that is already a valid iterator, and it also implements [Symbol.iterator]() itself. Writing *[Symbol.iterator]() removes the bookkeeping:
class Range {
constructor(start, end) {
this.start = start;
this.end = end;
}
*[Symbol.iterator]() {
for (let i = this.start; i <= this.end; i++) {
yield i;
}
}
}
console.log([...new Range(1, 3)]); // [1, 2, 3]
for (const n of new Range(4, 5)) console.log(n); // 4, then 5Once the method exists, every consumer of iterables works with your object:
| Consumer | Example | Result with `new Range(1, 3)` |
|---|---|---|
| `for...of` | `for (const n of r)` | 1, 2, 3 |
| Spread | `[...r]` | `[1, 2, 3]` |
| Destructuring | `const [a, b] = r` | `a = 1`, `b = 2` |
| `Array.from` | `Array.from(r)` | `[1, 2, 3]` |
| Constructors | `new Set(r)` | `Set {1, 2, 3}` |
| `Promise.all` | `Promise.all(r)` | resolves to `[1, 2, 3]` |
Common Errors
Other mistakes to watch for:
- Storing state on the iterable. If
next()advancesthis.indexon the instance, a second loop starts where the first ended. Keep state in the iterator. - Arrow functions for
next. That works, but a regular function under[Symbol.iterator]is needed if you rely onthisbeing the instance. - Infinite iterables. A generator with
while (true)is fine forfor...ofwith abreak, but spreading it hangs forever. - Forgetting cleanup. When a loop exits early via
break,return, or a thrown error, the engine calls the iterator's optionalreturn()method. Generators handle this for you: anyfinallyblock runs.
function* withCleanup() {
try {
yield 1;
yield 2;
} finally {
console.log('cleaned up');
}
}
for (const n of withCleanup()) {
console.log(n); // 1
break; // logs "cleaned up"
}Delegating to an Inner Collection
When your class wraps an array or Map, delegate instead of reimplementing:
class Playlist {
#songs = [];
add(song) { this.#songs.push(song); return this; }
[Symbol.iterator]() { return this.#songs[Symbol.iterator](); }
}
const p = new Playlist().add('Intro').add('Outro');
console.log([...p]); // ['Intro', 'Outro']Inside a generator, yield* this.#songs does the same thing.
Exercise
A class stores this.i = 0 in its constructor, and its [Symbol.iterator]() returns this, with next() incrementing this.i. Spreading an instance twice gives [1, 2, 3] and then []. Why, and how do you fix it?
Show answer
The instance is its own iterator, so the position (this.i) persists after the first pass is exhausted. The second spread calls next() on an iterator that is already done. Fix it by creating fresh state on each call: return a new object with its own counter from [Symbol.iterator](), or make the method a generator (*[Symbol.iterator]()), which creates a new iterator every time.
Exercise
Write an iterable object evens whose [Symbol.iterator] yields 0, 2, 4, 6, 8 so that [...evens] returns [0, 2, 4, 6, 8].
Show answer
const evens = { *[Symbol.iterator]() { for (let i = 0; i <= 8; i += 2) yield i; } }; Spreading it calls the generator method, which produces a fresh iterator that yields the five values and then reports done.