Sub topic 6
Building a Custom Iterable by Hand
This chapter assumes you know the iterable and iterator protocols from earlier chapters: an iterable has a [Symbol.iterator]() method, and that method returns an iterator whose next() returns { value, done }. You should also be comfortable with classes and closures.
Here you will implement both protocols yourself. Every for...of loop, spread, and destructuring pattern will then work on your own object.
The plan
A custom iterable needs two parts:
- An iterable object with a
[Symbol.iterator]()method. - An iterator object, returned by that method, with a
next()method.
The example is a Range class that produces the integers from start up to, but not including, 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;
}
};
}
}
const r = new Range(1, 4);
console.log([...r]); // [ 1, 2, 3 ]
console.log([...r]); // [ 1, 2, 3 ] (a fresh iterator each time)
for (const n of r) {
console.log(n); // 1, 2, 3
}How the pieces fit
The iteration state is the current variable. It lives in a closure created by each call to [Symbol.iterator](). Each loop or spread calls that method again and gets a new counter, so you can iterate the same Range any number of times, and two loops over it can even run at once without interfering.
The returned iterator also has its own [Symbol.iterator]() that returns this. That makes the iterator iterable too, so you can pass a partly used iterator to for...of and it carries on from where it stopped. Built-in iterators behave the same way.
Common errors
| Mistake | Symptom | Fix |
|---|---|---|
| Storing `current` on `this` (the Range) | Second loop yields nothing | Keep state inside the iterator or its closure |
| Forgetting `done: true` | Infinite loop | Return `{ value: undefined, done: true }` at the end |
| Making `next` an arrow function that uses `this` | `this` is wrong or undefined | Use closure variables, or a regular method |
| Returning a bare value from `next()` | `TypeError` or `undefined` results | Always return a `{ value, done }` object |
Exercise
Add an optional third constructor argument, step (default 1), to Range so that [...new Range(0, 10, 3)] returns [0, 3, 6, 9]. What must change in the code?
Show answer
Store it with this.step = step in the constructor (with step = 1 as the default parameter), capture const step = this.step inside [Symbol.iterator](), and in next() return { value: current, done: false } after advancing with current += step. For example: const value = current; current += step; return { value, done: false };. The current < end check stays the same.
Exercise
Given const it = new Range(1, 5)[Symbol.iterator](); it.next(); what does [...it] produce, and why?
Show answer
[2, 3, 4]. The iterator's own [Symbol.iterator]() returns this, so spread continues with the same iterator, which has already used up the value 1.