Sub topic 2
Iterables and Symbol.iterator
This chapter assumes you know JavaScript functions, objects, and methods, and that you have used arrays, Map, Set, spread, and destructuring.
What makes a value iterable
An iterable is any value that can hand out an iterator on request. The iterable protocol spells out how that request works. The value must have a method stored under the key Symbol.iterator, and calling that method must return an iterator object. The next chapter covers what an iterator does. For now, treat it as an object that delivers values one at a time.
Symbol.iterator is a built-in symbol, also called a well-known symbol. It is a unique key that cannot collide with an ordinary string property name such as "iterator". That is why the language can use it as a hook without breaking existing objects that happen to have an iterator property.
const isIterable = value =>
value != null && typeof value[Symbol.iterator] === 'function';
console.log(isIterable([1, 2])); // true
console.log(isIterable('hi')); // true
console.log(isIterable(new Map())); // true
console.log(isIterable({ a: 1 })); // false
console.log(isIterable(42)); // false
console.log(isIterable(null)); // falseThe check uses a property lookup, so the method can come from the prototype chain. Arrays don't store Symbol.iterator on each array. They inherit it from Array.prototype.
How consumers use the protocol
Features such as for...of and spread do not care what kind of collection they receive. They follow the same steps every time:
The common error is passing a plain object to for...of. Plain objects have no Symbol.iterator method:
const settings = { theme: 'dark', size: 12 };
try {
for (const entry of settings) {
console.log(entry);
}
} catch (err) {
console.log(err instanceof TypeError, err.message);
// true settings is not iterable
}
// Fix: iterate an iterable view of the object instead
for (const [key, value] of Object.entries(settings)) {
console.log(key, value); // theme dark, then size 12
}A fresh iterator on every call
A well-behaved iterable returns a new iterator each time Symbol.iterator is called. Each new iterator keeps its own position, so you can loop over the same array twice, or run two loops over it at once, and the loops don't interfere.
const nums = [10, 20];
const it1 = nums[Symbol.iterator]();
const it2 = nums[Symbol.iterator]();
console.log(it1 === it2); // false
console.log([...nums]); // [ 10, 20 ]
console.log([...nums]); // [ 10, 20 ]Not every iterable behaves this way. Some objects return the same iterator every time, and those can be consumed only once. A later chapter on pitfalls covers this case.
| Value | Has `Symbol.iterator`? | Works with `for...of`? |
|---|---|---|
| Array, String, Map, Set | Yes (inherited) | Yes |
| Plain object `{}` | No | No, throws TypeError |
| `null`, `undefined`, numbers | No | No, throws TypeError |
Exercise
Why does typeof new Set()[Symbol.iterator] print "function" even though you never assigned that property, and what happens if you run [...{ x: 1 }]?
Show answer
Set instances inherit the Symbol.iterator method from Set.prototype, and the property lookup finds it through the prototype chain. Spreading { x: 1 } throws a TypeError because plain objects have no Symbol.iterator method, so the object is not iterable.
Exercise
What two conditions does the iterable protocol require of a value?
Show answer
The value must have a method under the key Symbol.iterator, either its own or inherited, and calling that method must return an iterator object.