Sub topic 13
Under the Hood: Symbol.iterator and next()
This chapter assumes you already know for...of syntax and the built-in iterables (arrays, strings, Maps, Sets). It also assumes you know object literals, computed property keys such as [key]: value, and method shorthand. Here we look at what for...of does each time it runs. Once you know the mechanism, error messages like "is not iterable" become easier to read, and you will see why some iterators work only once.
Two protocols, two roles
for...of depends on two small contracts, called protocols, defined by the language.
- An iterable is any value that has a method under the key
Symbol.iterator. Calling that method returns an iterator. - An iterator is an object with a
next()method. Each call tonext()returns an iterator result, which is an object of the shape{ value, done }.
Symbol.iterator is a built-in symbol, a unique property key that cannot collide with any string key. Arrays, strings, Maps, Sets, arguments and DOM NodeLists all have a method under this key. Plain objects do not, which is why for...of rejects them.
| Role | What it must have | What it gives back |
|---|---|---|
| Iterable | A `[Symbol.iterator]()` method | A fresh or reused iterator |
| Iterator | A `next()` method | `{ value, done }` objects |
| Iterator result | `done` (boolean) and `value` | One step of data, or the end signal |
Driving an iterator by hand
The quickest way to see the protocol is to get an iterator yourself and call next():
const iterator = ['a', 'b'][Symbol.iterator]();
console.log(iterator.next()); // { value: 'a', done: false }
console.log(iterator.next()); // { value: 'b', done: false }
console.log(iterator.next()); // { value: undefined, done: true }for...of follows the same steps. The loop below does roughly what for (const letter of letters) does:
const letters = ['a', 'b', 'c'];
const it = letters[Symbol.iterator]();
let result = it.next();
while (!result.done) {
const letter = result.value;
console.log(letter);
result = it.next();
}
// a
// b
// cThe real loop also checks types, and it calls the iterator's optional return() method when you exit early. The chapter "break, continue and Early Exit" covers that part.
Iterators are lazy
The loop calls next() only when it needs the next value. Nothing is computed ahead of time and no array of results is built. This is why an iterator can describe an endless sequence: the loop stops pulling when you break. It is also why the built-in array iterator reads the array's current length on every step, so changes made during the loop show up in later steps. "Changing a Collection While You Loop" covers that topic.
A hand-written iterable
You can satisfy both protocols with plain objects. The later chapter "Making Your Own Objects Iterable" shows the shorter generator form. The long form below shows each part:
const countdown = {
from: 3,
[Symbol.iterator]() {
let current = this.from;
return {
next() {
if (current > 0) {
return { value: current--, done: false };
}
return { value: undefined, done: true };
}
};
}
};
for (const n of countdown) {
console.log(n);
}
// 3
// 2
// 1
console.log([...countdown]); // [3, 2, 1]Every call to countdown[Symbol.iterator]() creates a new current variable, so you can loop over countdown any number of times. Each loop gets its own independent iterator.
Iterables vs iterators: the one-shot trap
Built-in iterators are also iterables. Their [Symbol.iterator]() method returns the iterator itself. That lets you pass map.entries() or arr.values() straight to for...of. It also means such an iterator is used up after one pass:
const arr = [1, 2, 3];
const it = arr[Symbol.iterator]();
console.log(it[Symbol.iterator]() === it); // true
console.log([...it]); // [1, 2, 3]
console.log([...it]); // [] (already exhausted)
console.log([...arr]); // [1, 2, 3]
console.log([...arr]); // [1, 2, 3] (arrays hand out a fresh iterator each time)The default iterator of each built-in is one of its named methods:
console.log(Array.prototype[Symbol.iterator] === Array.prototype.values); // true
console.log(Set.prototype[Symbol.iterator] === Set.prototype.values); // true
console.log(Map.prototype[Symbol.iterator] === Map.prototype.entries); // trueThat is why for...of over a Map gives [key, value] pairs while over a Set it gives plain values.
The `value` on the final result is ignored
When next() returns done: true, for...of exits without reading value. A finishing value never reaches the loop body or spread:
const oneThenStop = {
[Symbol.iterator]() {
let sent = false;
return {
next() {
if (!sent) {
sent = true;
return { value: 'kept', done: false };
}
return { value: 'ignored', done: true };
}
};
}
};
console.log([...oneThenStop]); // ['kept']Common errors and what they mean
Most iteration errors are TypeErrors thrown at one of the protocol's checkpoints. The exact wording differs between engines. The messages below come from V8, the engine in Chrome and Node.js.
| Message (V8) | Cause |
|---|---|
| `obj is not iterable` | The value has no callable `[Symbol.iterator]`, for example a plain object, `null` or a number |
| `Result of the Symbol.iterator method is not an object` | `[Symbol.iterator]()` returned a primitive |
| `Iterator result undefined is not an object` | `next()` forgot to return `{ value, done }` |
const cases = {
plainObject: {},
primitiveIterator: { [Symbol.iterator]: () => 42 },
missingResult: { [Symbol.iterator]: () => ({ next() {} }) }
};
for (const [name, value] of Object.entries(cases)) {
try {
for (const x of value) {}
} catch (err) {
console.log(name, err instanceof TypeError, err.message);
}
}
// plainObject true ...is not iterable
// primitiveIterator true Result of the Symbol.iterator method is not an object
// missingResult true Iterator result undefined is not an objectTo test whether a value can be iterated before you use it, check for the method:
function isIterable(value) {
return value != null && typeof value[Symbol.iterator] === 'function';
}
console.log(isIterable('abc')); // true
console.log(isIterable(new Set())); // true
console.log(isIterable({})); // false
console.log(isIterable(null)); // falseThe check works for string primitives because property access on a primitive looks up String.prototype, where the method lives.
Who else speaks the protocol
The same protocol drives much more than for...of. A value that works in a for...of loop works in all of these:
| Consumer | Example |
|---|---|
| Spread into an array or call | `[...set]`, `Math.max(...iter)` |
| Array destructuring | `const [first, second] = countdown;` |
| `Array.from` | `Array.from(map.keys())` |
| Collection constructors | `new Set(iter)`, `new Map(pairs)` |
| Promise combinators | `Promise.all(iterableOfPromises)` |
| Generator delegation | `yield* iter` |
Array destructuring pulls only the values it needs. const [first] = countdown; calls next() once, takes 3, and then closes the iterator.
Exercise
Given const s = new Set(['x', 'y']); const it = s.values();, what do these four lines print, in order? console.log(it.next()); console.log([...it]); console.log([...it]); console.log([...s]);
Show answer
{ value: 'x', done: false }, then ['y'] because spread continues from where the iterator stopped, then [] because the iterator is exhausted, then ['x', 'y'] because the Set itself hands out a fresh iterator.
Exercise
Write an object letters that is iterable without using a generator, yields 'a', 'b' and 'c', and can be spread twice with the same result each time.
Show answer
const letters = { [Symbol.iterator]() { const items = ['a', 'b', 'c']; let i = 0; return { next() { return i < items.length ? { value: items[i++], done: false } : { value: undefined, done: true }; } }; } }; Each spread calls [Symbol.iterator]() again, which creates a new i, so [...letters] gives ['a', 'b', 'c'] every time.
Exercise
A colleague's iterator has next() { if (i < 3) return { value: i++, done: false }; }. Using it in for...of throws a TypeError after three values. Why, and what is the fix?
Show answer
Once i reaches 3, the function reaches its end and returns undefined. The loop expects an object, so it throws "Iterator result undefined is not an object". The fix is to return { value: undefined, done: true } when the sequence ends.