Sub topic 15
Making Your Own Objects Iterable
This chapter assumes you know classes, the iterable protocol from the previous chapter (Symbol.iterator returns an object with next()), and basic function* generator syntax.
The Goal
for...of works with any object that has a [Symbol.iterator] method. You can add that method to your own classes, and their instances then work in for...of, in spread syntax ([...obj]), in Array.from, and in destructuring.
Using a Generator Method
You could write next() by hand and keep track of { value, done } yourself. A generator method is shorter. A generator already returns an iterator, and that iterator follows the protocol.
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]The * before the computed key [Symbol.iterator] makes this a generator method. Each yield produces one value for the loop. When the method returns, the iterator reports done: true and the loop ends.
Each Loop Gets a Fresh Iterator
for...of calls [Symbol.iterator]() every time a loop starts, so you can loop over the same Range more than once. A generator object is different. It is an iterator that returns itself from [Symbol.iterator], so it can only be used once.
function* oneToThree() {
yield 1; yield 2; yield 3;
}
const gen = oneToThree();
console.log([...gen]); // [1, 2, 3]
console.log([...gen]); // [] (already exhausted)
const range = new Range(1, 4);
console.log([...range]); // [1, 2, 3]
console.log([...range]); // [1, 2, 3]Common Errors
| Mistake | Symptom |
|---|---|
| Forgetting the `*` on the method | `TypeError: Result of the Symbol.iterator method is not an object`, or a loop that never ends |
| Naming the method `iterator` instead of `[Symbol.iterator]` | `TypeError: ... is not iterable` |
| Storing one generator object and reusing it | The second loop yields nothing |
| Using an arrow function for the method | Syntax error, because arrow functions cannot be generators |
Exercise
Give a Stack class that stores values in this.items (an array) a [Symbol.iterator] method that yields items from the top of the stack (the last element) down to the bottom.
Show answer
Add *[Symbol.iterator]() { for (let i = this.items.length - 1; i >= 0; i--) { yield this.items[i]; } }. If items is [1, 2, 3], then [...stack] gives [3, 2, 1].
Exercise
Why does [...new Range(0, 2)] work every time, while spreading the same generator object a second time gives an empty array?
Show answer
Every spread calls Range's [Symbol.iterator](), which creates a new generator. A generator object returns itself from [Symbol.iterator], so a second spread continues from the already-finished state.