Sub topic 5
What Consumes Iterables: for...of, Spread, Destructuring, and More
This chapter assumes you know the iterable and iterator protocols from the earlier chapters, and that you are comfortable with spread syntax, destructuring, and the basics of Map and Set.
An iterable is only useful when something reads it. JavaScript has several built-in features that read iterables, called consumers. Each consumer does the same thing internally. It calls [Symbol.iterator]() to get an iterator, then calls next() until it has the values it needs or done is true.
The common consumers
| Consumer | Example | What it does with the values |
|---|---|---|
| `for...of` | `for (const x of it) {}` | Runs the loop body once per value |
| Array spread | `[...it]` | Copies every value into a new array |
| Argument spread | `Math.max(...it)` | Passes every value as an argument |
| Array destructuring | `const [a, b] = it` | Pulls only as many values as it needs |
| `Array.from` | `Array.from(it, fn)` | Builds an array, with an optional mapping function |
| Constructors | `new Map(it)`, `new Set(it)` | Fill a collection from the values |
| Promise combinators | `Promise.all(it)` | Wait on each value |
Consumers in action
const map = new Map([['x', 1], ['y', 2]]);
for (const [key, value] of map) {
console.log(key, value); // x 1, then y 2
}
const [first, ...rest] = 'hey';
console.log(first, rest); // h [ 'e', 'y' ]
console.log(Array.from(new Set([3, 3, 4]))); // [ 3, 4 ]The Map loop combines two consumers. for...of pulls each [key, value] entry, and array destructuring then unpacks that entry. Destructuring the string 'hey' works because strings are iterable. The rest element ...rest collects whatever values are left.
Common errors
Some syntax looks similar but does not use the protocol.
- Object spread
{ ...obj }copies own enumerable properties and never callsSymbol.iterator.{ ...new Set([1, 2]) }gives{}. for...inloops over property keys, not iterable values. On an array it gives the string indexes'0','1', and so on.- Plain objects are not iterable.
for (const x of { a: 1 })andconst [a] = {}both throwTypeError: ... is not iterable. UseObject.entries(obj)to get an iterable array of entries. - Array-likes such as
{ length: 2, 0: 'a', 1: 'b' }work withArray.frombut fail with spread.Array.fromfalls back to readinglengthand indexes. Spread requiresSymbol.iterator.
Exercise
What does each line log, and which line throws? const s = new Set(['a', 'b']); then (1) console.log([...s]); (2) console.log({ ...s }); (3) const [x] = s; console.log(x); (4) for (const v of { a: 1 }) console.log(v);
Show answer
(1) logs [ 'a', 'b' ] because array spread uses the iterator. (2) logs {} because object spread copies own enumerable properties, and a Set has none. (3) logs 'a' because destructuring pulls one value. (4) throws TypeError because a plain object has no Symbol.iterator method.
Exercise
Why does Array.from({ length: 2, 0: 'a', 1: 'b' }) return [ 'a', 'b' ] while [...{ length: 2, 0: 'a', 1: 'b' }] throws?
Show answer
Array.from accepts array-like objects and falls back to reading length and the numeric indexes when there is no Symbol.iterator. Spread accepts only iterables, so it throws a TypeError.