Sub topic 7
Making Objects Iterable with Symbol.iterator
This chapter assumes you know ES6 classes, computed property names, for...of loops, and spread syntax. It also assumes you have read the earlier chapters on symbols as property keys and on well-known symbols. Generator functions (function*) appear throughout. You only need to know that yield hands out one value at a time.
Symbol.iterator is the most widely used well-known symbol. When an object has a method stored under this key, every built-in feature that consumes a sequence can use it: for...of, spread, array destructuring, Array.from, new Set(...), Promise.all, and more. This chapter explains the protocol behind that method, shows two ways to implement it, and covers the mistakes that cause most bugs.
The Iteration Protocol
Two roles make up the protocol.
- An iterable is an object with a method at
[Symbol.iterator]. Calling that method returns an iterator. - An iterator is an object with a
next()method. Each call tonext()returns a result object of the shape{ value, done }.
When done is false, value is the next item. When done is true, the sequence is over, and consumers ignore value.
You can drive the protocol by hand on a built-in iterable to see these pieces:
const letters = ['a', 'b'];
const it = letters[Symbol.iterator]();
console.log(it.next()); // { value: 'a', done: false }
console.log(it.next()); // { value: 'b', done: false }
console.log(it.next()); // { value: undefined, done: true }The language looks up the iterator method through a symbol and never through a string name. A symbol key cannot clash with any property a user might define. An object can have a data property called "iterator" and still have a separate iteration method.
Implementing It with a Generator
The shortest way to make a class iterable is a generator method under the symbol key. A generator function returns a generator object, and that object is already an iterator. It is also an iterable whose [Symbol.iterator]() returns itself.
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 5
const [first, second] = new Range(10, 20);
console.log(first, second); // 10 11
console.log(Array.from(new Range(1, 4), n => n * n)); // [1, 4, 9, 16]The * before the computed key [Symbol.iterator] makes the method a generator. A regular method body runs this against the instance, so this.start and this.end work as expected.
You can also delegate to an existing iterable with yield*. This works well for wrapper classes:
class TagList {
#tags = new Set();
add(tag) {
this.#tags.add(tag.toLowerCase());
return this;
}
*[Symbol.iterator]() {
yield* this.#tags;
}
}
const tags = new TagList().add('JS').add('js').add('Node');
console.log([...tags]); // ['js', 'node']The class shows its contents to iteration without exposing the internal Set. Callers cannot call .delete() on the set, because they never receive it.
Implementing It by Hand
Generators hide the protocol. If you write the iterator object yourself, you control every step, and you can see what generators do for you.
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 };
},
[Symbol.iterator]() {
return this;
}
};
}
}
console.log([...new Countdown(3)]); // [3, 2, 1, 0]Here is what the code does:
- The state (
current) lives in a closure that each call to[Symbol.iterator]()creates. Each loop therefore gets its own counter. next()always returns an object, including at the end.- The iterator also defines
[Symbol.iterator]() { return this; }. This makes the iterator itself iterable, so code likefor (const x of someIterator)works. All built-in iterators follow this convention, and generators follow it automatically.
Early Exit and the return() Method
An iterator can define an optional return() method. Consumers call it when they stop before the sequence ends, for example on break, on a thrown error, on return inside the loop, or when destructuring takes only a few items. Use return() to release resources such as file handles, timers, or locks.
const numbers = {
[Symbol.iterator]() {
let i = 0;
return {
next() {
i++;
return i <= 5
? { value: i, done: false }
: { value: undefined, done: true };
},
return() {
console.log('cleanup');
return { value: undefined, done: true };
}
};
}
};
for (const n of numbers) {
if (n === 2) break;
console.log(n);
}
// 1
// cleanup
const [only] = numbers; // logs "cleanup" too
console.log(only); // 1return() is not called when the sequence runs to completion, because the iterator already knows it is finished. In a generator, try...finally gives you the same hook. The finally block runs on early exit because the consumer calls the generator's built-in return().
function* withCleanup() {
try {
yield 1;
yield 2;
} finally {
console.log('released');
}
}
for (const n of withCleanup()) {
console.log(n);
break;
}
// 1
// releasedWhere Iterables Are Consumed
| Consumer | Example | Calls `return()` on early exit |
|---|---|---|
| `for...of` | `for (const x of it) {}` | Yes, on `break`, `throw`, or `return` |
| Spread | `[...it]`, `fn(...it)` | No early exit possible |
| Array destructuring | `const [a, b] = it` | Yes, if items remain |
| `Array.from` | `Array.from(it, mapFn)` | Yes, if `mapFn` throws |
| Collection constructors | `new Set(it)`, `new Map(it)` | Yes, on error |
| Promise combinators | `Promise.all(it)` | Yes, on error |
| `yield*` | `yield* it` | Forwards the outer generator's `return()` |
Object spread ({...obj}) and for...in do not use the iteration protocol. They work on enumerable own properties, which is a separate mechanism.
Re-iterable vs One-Shot Iterables
This distinction causes more confusion than any other part of the protocol.
- A re-iterable object, such as an array, a
Set, or theRangeclass above, returns a fresh iterator from each[Symbol.iterator]()call. You can loop over it many times. - A one-shot iterable is an iterator that returns
this. A generator object is one. After it is exhausted, it stays exhausted.
function* pair() {
yield 1;
yield 2;
}
const g = pair();
console.log([...g]); // [1, 2]
console.log([...g]); // [] (already exhausted)
const r = new Range(1, 2);
console.log([...r]); // [1, 2]
console.log([...r]); // [1, 2] (fresh generator each time)Lazy and Infinite Sequences
Iterators produce values on demand, so a sequence can be infinite as long as the consumer stops. Spreading an infinite iterator hangs the program. Pair it with a helper that limits the count:
function* naturals() {
let n = 0;
while (true) yield n++;
}
function* take(iterable, count) {
if (count <= 0) return;
for (const item of iterable) {
yield item;
if (--count === 0) return;
}
}
console.log([...take(naturals(), 3)]); // [0, 1, 2]When take returns, its inner for...of exits early, which calls return() on the naturals generator. Cleanup passes up the chain.
Common Errors
Spreading a plain object
Plain objects are not iterable. [...{ a: 1 }] throws TypeError: object is not iterable. Iterate over Object.entries(obj) instead, or define [Symbol.iterator] on the object.
Using an arrow function
const bad = {
items: [1, 2],
[Symbol.iterator]: () => this.items[Symbol.iterator]() // `this` is not `bad`
};Arrow functions do not bind their own this, and an arrow function cannot be a generator. Use method syntax: *[Symbol.iterator]() { yield* this.items; }.
Returning the wrong thing
[Symbol.iterator]() must return an object with next(). If it returns an array, for...of throws TypeError: Result of the Symbol.iterator method is not an object or reports that next is not a function, depending on the engine. If next() returns a non-object, it throws as well.
Assigning the key as a string
obj['Symbol.iterator'] = ... creates an ordinary string-keyed property, and the language ignores it. The key must be the symbol value Symbol.iterator.
Checking for iterability
To test whether a value can be iterated, check for the method:
function isIterable(value) {
return value != null && typeof value[Symbol.iterator] === 'function';
}
console.log(isIterable([1])); // true
console.log(isIterable('hi')); // true (strings iterate by code point)
console.log(isIterable({ a: 1 })); // false
console.log(isIterable(null)); // falseStrings iterate by Unicode code point, not by UTF-16 unit. [...'a😀'].length is 2, while 'a😀'.length is 3.
Exercise
Write a class Matrix that stores rows as an array of arrays and is iterable over every cell in row-major order, so [...new Matrix([[1, 2], [3, 4]])] gives [1, 2, 3, 4]. Make sure it can be iterated more than once.
Show answer
Use a generator method so each call creates a fresh iterator: class Matrix { constructor(rows) { this.rows = rows; } *[Symbol.iterator]() { for (const row of this.rows) { yield* row; } } }. Because [Symbol.iterator]() returns a new generator on every call, spreading the same instance twice gives [1, 2, 3, 4] both times.
Exercise
A function summarize(iterable) computes const count = [...iterable].length; and then runs for (const x of iterable) total += x;. It works for arrays but returns a total of 0 for a generator. Why, and how do you fix it?
Show answer
A generator object is a one-shot iterable. Its [Symbol.iterator]() returns itself, so the first spread exhausts it and the for...of loop receives nothing. Fix it by materializing the input once, const items = [...iterable];, and then using items.length and looping over items.
Exercise
In a hand-written iterator, a for...of loop that uses break should close a database cursor. Which method do you add, what must it return, and does it run when the loop finishes normally?
Show answer
Add a return() method to the iterator that closes the cursor and returns an object such as { value: undefined, done: true }. Consumers call it only on early exit (break, throw, return, or partial destructuring). It does not run when next() reports done: true, so close the cursor at that point too, or use a generator with try...finally, which covers both cases.