Sub topic 5
What Consumes Iterables: for...of, Spread, Destructuring, and More
This chapter assumes you know how to write functions, arrow functions, and object literals, how spread and destructuring work on arrays, and how promises behave. It also assumes the previous chapters: an iterable has a [Symbol.iterator]() method, and that method returns an iterator whose next() produces { value, done } results.
An iterable by itself does nothing. Something has to ask it for values. JavaScript has a fixed set of language features and built-in functions that do the asking. They all run the same steps, so once you know those steps you can predict how any of them will treat any iterable.
The shared algorithm
Every consumer in this chapter follows the same sequence:
- Read
obj[Symbol.iterator]. If it is missing or not a function, throw aTypeError. - Call it once to get an iterator.
- Call
iterator.next()repeatedly. Each result withdone: falsesupplies onevalue. - Stop when a result has
done: true. Itsvalueis ignored. A consumer can also stop early because it has all it needs.
Iteration is pull-based. The consumer decides when to ask for the next value and when to stop. The iterable only answers.
Watching a consumer pull
You can see these steps by wrapping an iterable so that every next() call gets logged. Each example below uses this helper:
function traced(iterable) {
return {
[Symbol.iterator]() {
console.log('Symbol.iterator called');
const it = iterable[Symbol.iterator]();
return {
next() {
const result = it.next();
console.log('next ->', result);
return result;
}
};
}
};
}
const [a, b] = traced([10, 20, 30]);
// Symbol.iterator called
// next -> { value: 10, done: false }
// next -> { value: 20, done: false }
console.log(a, b); // 10 20
const [x, ...rest] = traced([1, 2, 3]);
// Symbol.iterator called
// next -> { value: 1, done: false }
// next -> { value: 2, done: false }
// next -> { value: 3, done: false }
// next -> { value: undefined, done: true }
console.log(x, rest); // 1 [ 2, 3 ]Destructuring two names calls next() exactly twice and never reaches 30. A rest element (...rest) has to drain the iterator, so it keeps calling until done: true. This difference becomes important with expensive or infinite sources.
The consumers
| Consumer | Example | Pulls |
|---|---|---|
| `for...of` | `for (const v of it) {}` | Until done, `break`, `return`, or throw |
| Array spread | `[...it]` | Everything |
| Call spread | `f(...it)` | Everything |
| Array destructuring | `const [a, b] = it` | One value per position; all of them for `...rest` |
| `Array.from` | `Array.from(it, fn)` | Everything |
| Collection constructors | `new Map(it)`, `new Set(it)`, `new WeakMap(it)`, `new WeakSet(it)` | Everything |
| `Object.fromEntries` | `Object.fromEntries(it)` | Everything, as `[key, value]` pairs |
| Promise combinators | `Promise.all(it)`, `allSettled`, `race`, `any` | Everything |
| `yield*` | `yield* it` inside a generator | Covered in a later chapter |
for...of
for...of is the general-purpose consumer. Your loop body runs between next() calls, so you control the pace. With const or let, each pass gets a fresh binding, so closures created in the body capture the value from that pass. You can destructure in the loop head:
const scores = new Map([['ana', 9], ['ben', 7]]);
for (const [name, score] of scores) {
if (score < 8) continue;
console.log(name); // ana
}Spread in arrays and calls
Array spread collects every value into a new array. Call spread passes every value as a separate argument:
const unique = new Set([3, 7, 2, 7]);
console.log([...unique]); // [ 3, 7, 2 ]
console.log(Math.max(...unique)); // 7
console.log([0, ...'ab', ...unique]); // [ 0, 'a', 'b', 3, 7, 2 ]Call spread puts every value on the call stack as an argument. With hundreds of thousands of elements, Math.max(...huge) can throw RangeError: Maximum call stack size exceeded. For large inputs, use a loop or reduce.
Array.from versus spread
Array.from takes an iterable and an optional mapping function, and it builds the array in one pass. Unlike spread, it also accepts array-likes: objects that have a length and numeric keys but no Symbol.iterator.
console.log(Array.from(new Set([1, 2]), n => n * 10)); // [ 10, 20 ]
console.log(Array.from({ length: 3 }, (_, i) => i * 2)); // [ 0, 2, 4 ]
try {
console.log([...{ length: 3 }]);
} catch (e) {
console.log(e instanceof TypeError); // true (the object is not iterable)
}Array.from checks for Symbol.iterator first. It falls back to length and indexes only when that method is missing.
Collection constructors and Object.fromEntries
new Set(it) adds each value. new Map(it) and Object.fromEntries(it) expect each value to be a [key, value] pair. Each one reads index 0 and index 1 of the pair.
console.log(new Set('hello')); // Set(4) { 'h', 'e', 'l', 'o' }
const m = new Map(Object.entries({ a: 1, b: 2 }));
console.log(m.get('b')); // 2
console.log(Object.fromEntries(m)); // { a: 1, b: 2 }With Object.entries and Object.fromEntries together, you can move between plain objects and any iterable of pairs.
Promise combinators
Promise.all, Promise.allSettled, Promise.race, and Promise.any accept any iterable, not only arrays. Values that are not promises are treated as already resolved:
const jobs = new Set([Promise.resolve(1), 2]);
Promise.all(jobs).then(console.log); // [ 1, 2 ]Things that look like consumers but are not
for...in also does not consume iterables. It loops over enumerable property keys, which are strings, and that includes inherited ones:
for (const k in ['a', 'b']) console.log(k, typeof k); // 0 string, 1 string
for (const v of ['a', 'b']) console.log(v); // a, bUse for...of for values. Keep for...in for inspecting the keys of plain objects, and even there Object.keys is usually clearer.
Common errors
"x is not iterable"
Plain objects have no Symbol.iterator, so this throws:
const config = { host: 'localhost', port: 8080 };
try {
for (const entry of config) {}
} catch (e) {
console.log(e.message); // config is not iterable
}
for (const [key, value] of Object.entries(config)) {
console.log(key, value); // host localhost, port 8080
}The same error comes from [...config], const [a] = config, and new Map(config). The usual fix is to pick a view of the object: Object.keys, Object.values, or Object.entries. null and undefined throw the same way, which often means a function returned nothing when you expected an array.
Draining infinite iterables
Spread, Array.from, rest elements, the collection constructors, and the promise combinators all pull until done: true. If a source never finishes, these consumers never return, and the program hangs or runs out of memory. With an unbounded source, use for...of with a break, or destructure fixed positions without a rest element. The chapters on lazy sequences build safe tools for this.
Expecting the done value
The value that comes with done: true is thrown away by every consumer in this chapter. If your iterator returns a meaningful final value, for...of and spread will not show it to you.
Exercise
Using the traced helper from this chapter, how many times is next() called by const [, second] = traced(['a', 'b', 'c']), and what is second?
Show answer
Two times. The hole skips the first value, but the skipped value still has to be pulled with next(). The second call supplies 'b', so second is 'b'. Destructuring never asks for 'c'.
Exercise
What do [...new Map([['k', 1]])] and { ...new Map([['k', 1]]) } produce, and why are they different?
Show answer
Array spread produces [ [ 'k', 1 ] ], because it iterates the Map and a Map yields [key, value] entries. Object spread produces {}, because it copies own enumerable properties instead of iterating, and a Map stores its entries internally, not as properties.
Exercise
A function returns either an array or a NodeList-like object { length: 2, 0: 'x', 1: 'y' } that has no Symbol.iterator. Which single call turns both into a real array, and why does spread fail on one of them?
Show answer
Array.from(value). It uses Symbol.iterator when the value has one and falls back to length and indexes when it does not. Spread requires Symbol.iterator, so it throws a TypeError on the array-like object.