Sub topic 15
Making Your Own Objects Iterable
This chapter assumes you know how for...of consumes an iterable: it calls [Symbol.iterator]() and then calls next() until done is true. It also assumes you have seen generator functions (function* and yield) and JavaScript classes. Here you move from consuming iterables to building them. You will write an iterator by hand, replace it with a generator method, and avoid the mistakes that make custom iterables fail.
What "iterable" means for your own object
An object is iterable when it has a method stored under the key Symbol.iterator, and that method returns an iterator. An iterator is an object with a next() method that returns { value, done } result objects.
Once your object follows this contract, every language feature that consumes iterables accepts it. The list includes for...of, spread syntax, array destructuring, Array.from, new Map(...), new Set(...), Promise.all and yield*. You write the contract once and all of these work with no extra code.
Writing an iterator by hand
Start with the long form, so you can see each part of the contract. This Countdown class counts down from a starting number to zero.
class Countdown {
constructor(from) {
this.from = from;
}
[Symbol.iterator]() {
let current = this.from; // state lives in this closure, not on the instance
return {
next() {
if (current < 0) {
return { value: undefined, done: true };
}
return { value: current--, done: false };
},
// Make the iterator itself iterable, like built-in iterators are
[Symbol.iterator]() {
return this;
}
};
}
}
for (const n of new Countdown(3)) {
console.log(n);
}
// 3
// 2
// 1
// 0
console.log([...new Countdown(2)]); // [2, 1, 0]The design choice that matters most here is where the loop state lives. The variable current is created fresh inside each call to [Symbol.iterator](). Each loop therefore gets its own independent position. If you stored the position on this instead, two loops over the same object would interfere with each other, and a second loop would start where the first one stopped.
The short form: a generator method
A generator function returns a generator object. That object already has next(), returns correct result objects, is iterable itself, and implements return() so that break runs cleanup. If you define [Symbol.iterator] as a generator method, you get all of this for free.
class Range {
constructor(start, end) {
this.start = start;
this.end = end;
}
*[Symbol.iterator]() {
for (let i = this.start; i < this.end; i++) {
yield i;
}
}
}
for (const n of new Range(1, 4)) {
console.log(n);
}
// 1
// 2
// 3
console.log([...new Range(1, 4)]); // [1, 2, 3]
const [first, second] = new Range(10, 20);
console.log(first, second); // 10 11
console.log(Array.from(new Range(0, 3), x => x * 2)); // [0, 2, 4]The * in front of the computed key [Symbol.iterator] makes it a generator method. Destructuring pulls only two values, so the generator never computes the rest. Generators run lazily: a value is produced only when someone asks for it.
Iterating a data structure you built
Custom iterables work best for structures whose internals you want to hide. In this linked list, callers loop over values and never see the nodes.
class LinkedList {
constructor() {
this.head = null;
this.tail = null;
}
add(value) {
const node = { value, next: null };
if (this.tail) {
this.tail.next = node;
} else {
this.head = node;
}
this.tail = node;
return this;
}
*[Symbol.iterator]() {
for (let node = this.head; node !== null; node = node.next) {
yield node.value;
}
}
}
const list = new LinkedList().add('a').add('b').add('c');
for (const item of list) {
console.log(item);
}
// a
// b
// c
console.log(new Set(list).has('b')); // trueDelegating and offering several views
When your class wraps an existing collection, use yield* to pass its values through. You can also add named generator methods for other views, the same way Map offers keys(), values() and entries().
class Team {
constructor(name, members) {
this.name = name;
this.members = members;
}
// Default iteration: member names
*[Symbol.iterator]() {
yield* this.members;
}
// An extra view: [index, name] pairs
*entries() {
let i = 0;
for (const m of this.members) {
yield [i++, m];
}
}
}
const team = new Team('core', ['Ada', 'Alan', 'Grace']);
console.log([...team]); // ['Ada', 'Alan', 'Grace']
for (const [i, name] of team.entries()) {
console.log(i, name);
}
// 0 Ada
// 1 Alan
// 2 GraceIterables versus one-shot iterators
There is an important difference between an object that is iterable and an iterator that happens to be iterable. Range creates a new generator every time it is iterated, so you can loop over it as often as you like. A generator object is its own iterator. Once it is used up, it stays used up.
function* letters() {
yield 'a';
yield 'b';
}
const gen = letters();
console.log([...gen]); // ['a', 'b']
console.log([...gen]); // [] (already exhausted)
const r = new Range(1, 3);
console.log([...r]); // [1, 2]
console.log([...r]); // [1, 2] (fresh iterator each time)Infinite iterables
Nothing requires an iterator to finish. An infinite generator is safe with for...of as long as the loop body uses break or return. Spread, Array.from and destructuring with a rest element all try to read every value, so they will hang on an infinite source.
class Naturals {
*[Symbol.iterator]() {
let n = 0;
while (true) yield n++;
}
}
for (const n of new Naturals()) {
if (n > 3) break;
console.log(n);
}
// 0
// 1
// 2
// 3
// [...new Naturals()] would never finishCommon errors
| Symptom | Cause | Fix |
|---|---|---|
| `TypeError: ... is not iterable` | The method was named `iterator` or `'Symbol.iterator'` (a string key) | Use the computed key `[Symbol.iterator]` |
| `SyntaxError` on `yield` | The `*` before the method name is missing | Write `*[Symbol.iterator]() { ... }` |
| `TypeError` mentioning `next` | `[Symbol.iterator]` returned an array or another non-iterator | Return an iterator: `return this.items[Symbol.iterator]()` or use `yield*` |
| `TypeError: Iterator result ... is not an object` | `next()` returned a bare value instead of `{ value, done }` | Return a result object every time |
| Second loop yields nothing | Position stored on `this`, or a generator object was reused | Keep state local to each `[Symbol.iterator]()` call |
| Wrong `this` inside the generator | An arrow function was used (arrow functions cannot be generators) | Use method syntax |
Exercises
Exercise
Write a Grid class that takes a 2D array of rows and makes for...of yield every cell, row by row. For example, [...new Grid([[1, 2], [3, 4]])] should return [1, 2, 3, 4].
Show answer
class Grid { constructor(rows) { this.rows = rows; } [Symbol.iterator]() { for (const row of this.rows) { yield row; } } } — the generator method walks each row, and yield* passes that row's values through one at a time.
Exercise
A function printTwice(items) runs for (const x of items) console.log(x) two times in a row. Called with new Range(1, 3) it prints 1, 2, 1, 2. Called with letters() it prints only a, b. Why?
Show answer
Range's [Symbol.iterator] creates a new generator on every call, so each loop starts fresh. letters() returns a single generator object whose [Symbol.iterator] returns itself, so the first loop exhausts it and the second loop receives done: true immediately.
Exercise
The method [Symbol.iterator]() { return this.items; }, where this.items is an array, makes for...of throw a TypeError. Give two correct one-line fixes.
Show answer
Return an iterator instead of the array: [Symbol.iterator]() { return this.items[Symbol.iterator](); }, or use delegation: *[Symbol.iterator]() { yield* this.items; }.