Sub topic 6
Building a Custom Iterable by Hand
This chapter assumes you know closures, classes and methods, and computed property keys such as [Symbol.iterator]. It also assumes you have read the earlier chapters on the iterable and iterator protocols. In this chapter you write both protocols yourself, with no generators. Doing it by hand shows what a generator does for you later, and it is still the right tool when you need precise control over iterator state.
The two pieces you must supply
A custom iterable has two parts:
- The iterable is the object with a
[Symbol.iterator]()method. Each call to that method returns an iterator. - The iterator is the object with a
next()method. Each call tonext()returns a result object shaped{ value, done }.
Every consumer works the same way. for...of, spread, destructuring and Array.from call [Symbol.iterator]() once, then call next() repeatedly until they get done: true.
A Range class
The classic first example is a numeric range with an exclusive end.
class Range {
constructor(start, end) {
this.start = start;
this.end = end;
}
[Symbol.iterator]() {
let current = this.start;
const end = this.end;
return {
next() {
if (current < end) {
return { value: current++, done: false };
}
return { value: undefined, done: true };
},
[Symbol.iterator]() {
return this;
}
};
}
}
console.log([...new Range(1, 4)]); // [ 1, 2, 3 ]Some details here deserve a closer look.
State lives in a closure, not on the Range
current is a local variable captured by next(). Each call to [Symbol.iterator]() creates a new current. That means two loops over the same Range don't interfere with each other:
class Range {
constructor(start, end) {
this.start = start;
this.end = end;
}
[Symbol.iterator]() {
let current = this.start;
const end = this.end;
return {
next() {
return current < end
? { value: current++, done: false }
: { value: undefined, done: true };
},
[Symbol.iterator]() {
return this;
}
};
}
}
const r = new Range(0, 2);
for (const a of r) {
for (const b of r) {
console.log(a, b); // 0 0, 0 1, 1 0, 1 1
}
}The inner loop gets its own iterator, so the outer loop's position is untouched.
Copying `end` at the start
The line const end = this.end takes a snapshot of the bound when iteration begins. If you read this.end inside next() instead, code that changes the range in the middle of a loop would change that loop's stopping point. Neither choice is wrong, but you should pick one on purpose. Built-in arrays work the second way. An array iterator checks length on every step, which is why pushing to an array inside its own for...of loop can run forever.
The iterator is iterable too
The returned iterator also has [Symbol.iterator]() { return this; }. Built-in iterators all follow this convention, and it lets you pass a half-used iterator to for...of:
class Range {
constructor(start, end) {
this.start = start;
this.end = end;
}
[Symbol.iterator]() {
let current = this.start;
const end = this.end;
return {
next() {
return current < end
? { value: current++, done: false }
: { value: undefined, done: true };
},
[Symbol.iterator]() {
return this;
}
};
}
}
const it = new Range(1, 5)[Symbol.iterator]();
it.next(); // skip 1
for (const n of it) console.log(n); // 2, 3, 4Without that method, for (const n of it) throws TypeError: it is not iterable.
Iterating a data structure: a linked list
Ranges compute their values. Collections walk over stored data instead. A singly linked list shows the common pattern: keep a cursor in the closure and move it forward on each next().
class LinkedList {
constructor() {
this.head = null;
}
push(value) {
const node = { value, next: null };
if (!this.head) {
this.head = node;
} else {
let n = this.head;
while (n.next) n = n.next;
n.next = node;
}
return this;
}
[Symbol.iterator]() {
let node = this.head;
return {
next() {
if (node === null) return { value: undefined, done: true };
const value = node.value;
node = node.next;
return { value, done: false };
},
[Symbol.iterator]() {
return this;
}
};
}
}
const list = new LinkedList().push('a').push('b').push('c');
console.log([...list]); // [ 'a', 'b', 'c' ]
const [first, ...others] = list;
console.log(first, others); // a [ 'b', 'c' ]
console.log(Array.from(list, s => s.toUpperCase())); // [ 'A', 'B', 'C' ]You implement the protocol once, and every consumer works with it.
Plain objects work too
You don't need a class. Any object with a [Symbol.iterator] method is iterable:
const weekdays = {
names: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri'],
[Symbol.iterator]() {
let i = 0;
const names = this.names;
return {
next: () =>
i < names.length
? { value: names[i++], done: false }
: { value: undefined, done: true }
};
}
};
console.log([...weekdays].join(' ')); // Mon Tue Wed Thu FriThis version skips the self-returning [Symbol.iterator] on the iterator, which is fine if nobody needs to iterate the iterator itself. It also uses an arrow function for next, which is safe here because the arrow function never reads this.
Common errors
| Mistake | What happens |
|---|---|
| `[Symbol.iterator]` returns an array or `undefined` instead of an object with `next()` | `TypeError` such as "Result of the Symbol.iterator method is not an object" or "next is not a function" |
| `next()` returns the bare value instead of `{ value, done }` | `TypeError: Iterator result 1 is not an object` |
| `done` is never set to `true` | Spread and `Array.from` never finish and use up memory |
| Iteration state is stored on `this` of the iterable | Nested loops and repeated passes interfere with each other |
| `next` uses `this.something` but is passed around detached | `this` is `undefined`, so you get a `TypeError` |
The fourth row is the most subtle. Compare this broken version:
class BadRange {
constructor(start, end) {
this.start = start;
this.end = end;
this.current = start; // shared by every loop
}
[Symbol.iterator]() {
return this;
}
next() {
return this.current < this.end
? { value: this.current++, done: false }
: { value: undefined, done: true };
}
}
const b = new BadRange(1, 3);
console.log([...b]); // [ 1, 2 ]
console.log([...b]); // [] (the shared cursor is already at the end)Here BadRange is its own iterator, so it can be used only once. That is sometimes what you want, as with a stream that can't be rewound. For a collection it is almost always a bug.
Infinite iterables
Nothing requires done to ever become true. An infinite iterable is valid as long as its consumer stops on its own:
const evens = {
[Symbol.iterator]() {
let n = 0;
return {
next() {
const value = n;
n += 2;
return { value, done: false };
}
};
}
};
for (const e of evens) {
if (e > 6) break;
console.log(e); // 0, 2, 4, 6
}Never spread an infinite iterable or destructure it with a rest element, because both try to read every value.
Exercise
Write a class Countdown whose constructor takes n and whose instances iterate n, n-1, ..., 1. Each instance must be iterable any number of times, and its iterator must itself be iterable. What does [...c, ...c] print for const c = new Countdown(2)?
Show answer
Keep the counter in a closure inside [Symbol.iterator]: [Symbol.iterator]() { let k = this.n; return { next() { return k > 0 ? { value: k--, done: false } : { value: undefined, done: true }; }, [Symbol.iterator]() { return this; } }; }. Each spread gets a fresh iterator, so the result is [ 2, 1, 2, 1 ].
Exercise
A teammate's iterator has next() { if (this.i < this.items.length) return this.items[this.i++]; return { done: true }; }. Spreading it throws a TypeError. Why, and what is the fix?
Show answer
While items remain, next() returns the raw item instead of a result object, and spread rejects any non-object result. Return { value: this.items[this.i++], done: false } instead. The final { done: true } already works because a missing value reads as undefined.