Sub topic 2
Iterables and Symbol.iterator
This chapter assumes you know JavaScript functions and closures, objects and classes, computed property keys ({ [key]: value }), and how spread and destructuring look in code. It covers the first half of the iteration contract: what makes a value iterable. The next chapter covers the object that iteration hands back, the iterator, and its next() method.
The working model
An iterable is any value that has a method stored under the key Symbol.iterator. When that method is called, it returns an iterator, which is the object that actually produces values one at a time.
That is the entire iterable protocol. No base class, interface keyword, or registration step is involved. for...of, spread, and array destructuring all do the same thing: they look up value[Symbol.iterator], call it, and work with whatever comes back.
The protocol has two sides:
| Role | What it must have | Who provides it | Example |
|---|---|---|---|
| Iterable | A `[Symbol.iterator]()` method that returns an iterator | The collection | An array, a string, a `Map` |
| Iterator | A `next()` method that returns `{ value, done }` | The object returned by `[Symbol.iterator]()` | `arr[Symbol.iterator]()` |
Keep these two roles apart. An array is iterable but is not an iterator, because it has no next() method. Most of the confusion in this area comes from treating the two as the same thing.
What Symbol.iterator is
Symbol.iterator is a well-known symbol, meaning a symbol value built into the language that the engine itself checks for. A symbol is a primitive that is guaranteed unique, so it can work as a property key without clashing with any string key.
const arr = [10, 20];
console.log(typeof Symbol.iterator); // 'symbol'
console.log(typeof arr[Symbol.iterator]); // 'function'
console.log(arr[Symbol.iterator] === Array.prototype[Symbol.iterator]); // true
console.log(arr[Symbol.iterator] === arr.values); // true
console.log(typeof {}[Symbol.iterator]); // 'undefined'Three details stand out here:
- The array has no
Symbol.iteratorproperty of its own. It inherits one fromArray.prototype, like any other method. Iterability goes through normal prototype lookup. - For arrays, the iterator method is the same function as
values(). This is whyfor...ofover an array gives you elements and not indexes. - A plain object literal inherits from
Object.prototype, andObject.prototypedefines noSymbol.iterator. Plain objects are not iterable.
Why a symbol and not a string name
If the protocol used a string key such as "iterator", any existing object that happened to have an iterator property would suddenly look iterable to the language, and probably break. A symbol key avoids that collision. It also keeps the method out of the usual property listings:
const team = {
members: ['Ana', 'Ben'],
[Symbol.iterator]() {
return this.members[Symbol.iterator]();
}
};
console.log([...team]); // [ 'Ana', 'Ben' ]
console.log(Object.keys(team)); // [ 'members' ]
console.log(JSON.stringify(team)); // {"members":["Ana","Ben"]}
console.log(Object.getOwnPropertySymbols(team)); // [ Symbol(Symbol.iterator) ]team here is a complete, working iterable. It doesn't build an iterator itself. It hands back the iterator of its internal array, which is a common and fully valid way to make a wrapper object iterable. Chapter 6 shows how to write the iterator by hand.
What a consumer does, step by step
Every built-in consumer runs the same internal steps (the spec calls this operation GetIterator). Knowing these steps tells you exactly which errors you can get and when.
Some consequences follow from these steps:
- The lookup happens at consumption time. Nothing is checked when the object is created. You can add or replace
[Symbol.iterator]later, and the next loop uses the new method. - The method is called as a method.
thisis the iterable. That is whyteamabove uses method shorthand. An arrow function would capture the outerthisandthis.memberswould beundefined. - The return value must be an object. The engine does not check that it has a working
next()until it first callsnext(). It does reject primitives right away.
const broken = {
[Symbol.iterator]() {
return 42;
}
};
try {
[...broken];
} catch (e) {
console.log(e instanceof TypeError); // true
}
const broken2 = {
[Symbol.iterator]: () => this.items[Symbol.iterator]()
};
try {
for (const x of broken2) {}
} catch (e) {
console.log(e instanceof TypeError); // true (this is not broken2)
}Checking whether a value is iterable
No built-in isIterable exists, but the check follows directly from the protocol:
function isIterable(value) {
return value != null && typeof value[Symbol.iterator] === 'function';
}
console.log(isIterable([1, 2])); // true
console.log(isIterable('abc')); // true
console.log(isIterable(new Map())); // true
console.log(isIterable({ a: 1 })); // false
console.log(isIterable(42)); // false
console.log(isIterable(null)); // falseStrings are primitives, yet 'abc'[Symbol.iterator] works. Reading a property on a primitive looks it up on that primitive's wrapper prototype, and String.prototype defines Symbol.iterator. Number.prototype does not, so numbers are not iterable.
This check only tells you the method exists. A function can still return a non-object or a broken iterator. Use the check to choose which code path to take, such as accepting either one item or a collection. Don't treat it as proof that iteration will succeed.
Iterating a plain object
A very common error is writing for (const x of someObject) and getting a TypeError. Plain objects were left non-iterable on purpose: an object could mean keys, values, or pairs, and the language does not guess which. Pick one explicitly:
const prices = { apple: 1.2, pear: 0.9 };
for (const key of Object.keys(prices)) console.log(key); // apple, pear
for (const v of Object.values(prices)) console.log(v); // 1.2, 0.9
for (const [k, v] of Object.entries(prices)) console.log(k, v); // apple 1.2, pear 0.9These methods return arrays, and arrays are iterable. If you want key/value semantics with direct iteration, a Map is usually the better data structure.
Fresh iterators and iterators that are iterable
A well-behaved iterable returns a new iterator on each call. That way two loops over the same array don't interfere with each other:
const arr = ['a', 'b'];
const it1 = arr[Symbol.iterator]();
const it2 = arr[Symbol.iterator]();
console.log(it1 === it2); // false
console.log(it1[Symbol.iterator]() === it1); // trueThe second line shows a convention. Built-in iterators are also iterable, and their [Symbol.iterator]() returns this. This lets you pass an iterator that is already partly consumed to for...of, and the loop continues from where the iterator is. The catch is that such an object can only be traversed once. Chapter 18 returns to this one-shot behavior, because it causes real bugs.
Exercises
Exercise
Why does for (const x of { length: 2, 0: 'a', 1: 'b' }) throw, while Array.from({ length: 2, 0: 'a', 1: 'b' }) returns ['a', 'b']?
Show answer
The object is array-like but not iterable: it has no Symbol.iterator method, so for...of throws a TypeError. Array.from first checks for Symbol.iterator. When the method is missing, it falls back to treating the value as array-like and reads indexes 0 to length - 1.
Exercise
Make this object iterable over its tags array so that [...post] returns ['js', 'web'] without changing the tags property: const post = { title: 'Hi', tags: ['js', 'web'] };
Show answer
Add a method that delegates to the array's iterator: post[Symbol.iterator] = function () { return this.tags[Symbol.iterator](); }; It must be a regular function (or method shorthand), not an arrow function, so that this refers to post when the consumer calls it.
Exercise
An object defines [Symbol.iterator]() { return []; }. Does isIterable report true, and what happens with [...obj]?
Show answer
isIterable returns true because the method exists. The empty array passes the "result is an object" check, but it has no next() method, so spread throws a TypeError when it tries to call next(). The method must return an iterator, not another iterable.