Sub topic 8
Getting Results Out: toArray, reduce, and Friends
Helpers such as map, filter, take, and drop return new iterators. They describe work but do not do it. To get an actual result you need a consuming method. A consuming method pulls values from the iterator until it has an answer, then hands back a plain value instead of another iterator.
This chapter assumes you know the iteration protocol (next() returning { value, done }), generator functions, and the lazy behavior of helpers covered earlier. It also assumes you know Array.prototype.reduce, some, every, and find, because the iterator versions closely mirror them.
The Six Consumers on Iterator.prototype
ES2025 added six consuming methods to Iterator.prototype, next to the lazy helpers:
| Method | Returns | Stops early? | Safe on an infinite iterator? |
|---|---|---|---|
| `toArray()` | A new array of all values | No | No, it never finishes |
| `reduce(fn, initial?)` | The final accumulator | No | No |
| `forEach(fn)` | `undefined` | No | No |
| `some(fn)` | `true` or `false` | Yes, on the first `true` | Only if a match exists |
| `every(fn)` | `true` or `false` | Yes, on the first `false` | Only if a failure exists |
| `find(fn)` | The first matching value or `undefined` | Yes, on the first match | Only if a match exists |
Each of these is eager. Calling one starts the pulling immediately, and the method does not return until it has an answer. Pipelines also have other consumers: for...of, spread syntax ([...it]), Array.from(it), and destructuring all pull values in the same way. The methods above have the advantage that they sit at the end of a method chain.
toArray: Materialize Everything
toArray() collects every remaining value into a new array. Use it at the end of a pipeline when you want ordinary array data back.
const squaresOfEvens = [1, 2, 3, 4, 5, 6]
.values()
.filter((n) => n % 2 === 0)
.map((n) => n * n)
.toArray();
console.log(squaresOfEvens); // [4, 16, 36]toArray() takes no arguments. On an infinite sequence it runs forever and keeps growing memory, so put a take before it.
reduce: Fold Values into One
reduce(reducer, initialValue) works like the array version, with one difference in the callback arguments. The reducer receives (accumulator, value, counter). There is no fourth "source array" argument, because an iterator has no array behind it.
const total = [3, 4, 5].values().reduce((sum, x) => sum + x, 0);
console.log(total); // 12
const product = [3, 4, 5].values().reduce((acc, x) => acc * x);
console.log(product); // 60When you omit initialValue, the first value becomes the accumulator, and the reducer starts with the second value at counter 1. That shortcut breaks on an empty iterator:
try {
[].values().reduce((a, b) => a + b);
} catch (e) {
console.log(e instanceof TypeError); // true
}
console.log([].values().reduce((a, b) => a + b, 0)); // 0reduce can also build structured results without a temporary array. Here it counts words by length:
const words = ['map', 'filter', 'take', 'drop', 'reduce'];
const byLength = words.values().reduce((counts, word) => {
counts[word.length] = (counts[word.length] ?? 0) + 1;
return counts;
}, {});
console.log(byLength); // { '3': 1, '4': 2, '6': 2 }forEach: Side Effects Only
forEach(fn) calls fn(value, counter) for each value and returns undefined. Use it for logging, writing to a stream, or updating outside state. You cannot break out of it except by throwing. If you need to stop early, use for...of with break, or use some/find.
['a', 'b', 'c'].values().forEach((value, i) => {
console.log(i, value);
});
// 0 a
// 1 b
// 2 cA common mistake is writing const result = it.forEach(...) and expecting an array. The return value is always undefined. If you want transformed values, use map followed by toArray.
some, every, and find: Short-Circuiting Consumers
These three stop as soon as the answer is known. That property makes them usable on infinite sequences, provided the answer actually arrives.
function* naturals() {
let n = 0;
while (true) yield n++;
}
console.log(naturals().some((n) => n > 10)); // true
console.log(naturals().every((n) => n < 5)); // false
console.log(naturals().find((n) => n * n > 50)); // 8Each call creates a fresh generator, so the three lines do not interfere with each other. some stops at 11, every stops at 5, and find stops at 8.
The risk works the other way round. naturals().every((n) => n >= 0) never finds a failing value, so it never returns. The same applies to some or find with a predicate nothing satisfies. Short-circuiting is safe only if you know a deciding value exists.
Short-circuiting closes the source
When some, every, or find stops early, it calls the iterator's return() method. For a generator, that call runs its finally blocks, so cleanup code still executes:
function* letters() {
try {
yield 'a';
yield 'b';
yield 'c';
} finally {
console.log('closed');
}
}
console.log(letters().find((x) => x === 'b'));
// closed
// bThe generator never yields 'c'. The same closing happens if your callback throws during any consumer: the method closes the iterator, then lets the error propagate. A later chapter on early termination covers closing in detail.
Consumers Drain the Iterator
Every consumer advances the iterator it is called on, and those values are gone afterwards. A short-circuiting consumer leaves the iterator closed. That matters if you hold a reference to the pipeline:
const it = [1, 2, 3, 4].values();
console.log(it.find((n) => n === 2)); // 2
console.log(it.toArray()); // []find closed the array iterator when it stopped at 2, so toArray() gets nothing, not [3, 4]. If you need to continue after a partial read, use next() directly or restructure with drop.
Choosing a Consumer
- You need all values as data:
toArray(). - You need one combined value (sum, max, grouped object):
reducewith an initial value. - You need to perform an action per value and want no result:
forEach. - You need a yes/no answer about existence:
some. About all values:every. - You need the first matching value:
find. Note thatundefinedis ambiguous if the sequence can containundefined. - You need to stop on a condition and also keep partial state:
for...ofwithbreak.
Exercise
What does this code print, and why? function* g() { try { yield 1; yield 2; yield 3; } finally { console.log('done'); } } console.log(g().map((x) => x * 10).some((x) => x > 15));
Show answer
It prints "done" and then "true". some pulls 10 (not greater than 15), then 20, which satisfies the predicate. some then calls return() on the map helper, which closes the generator and runs its finally block before some returns true. The value 3 is never produced.
Exercise
A colleague writes const max = readings.values().filter((r) => r.valid).reduce((a, b) => Math.max(a, b.value)); and it sometimes throws a TypeError, and sometimes returns an object instead of a number. Explain both problems and fix the code.
Show answer
Without an initial value, the first valid reading object becomes the accumulator. If only one reading is valid, reduce returns that object. If none are valid, the iterator is empty and reduce throws a TypeError. With two or more, Math.max(object, number) compares NaN. Fix: readings.values().filter((r) => r.valid).reduce((a, r) => Math.max(a, r.value), -Infinity), which returns -Infinity when there are no valid readings.
Exercise
Which of these calls terminate? (1) naturals().find((n) => n < 0) (2) naturals().every((n) => n < 1000) (3) naturals().take(5).forEach(console.log) (4) naturals().some((n) => n % 7 === 0)
Show answer
(2), (3), and (4) terminate. (1) never finds a negative number, so it loops forever. (2) stops at 1000, the first failing value. (3) is bounded by take(5). (4) stops immediately at 0, since 0 % 7 === 0.