Sub topic 11
Array Methods or Iterator Helpers?
This chapter assumes you know the four core helpers (map, filter, take, drop), the consuming methods such as toArray, and how lazy pull-based evaluation works. It also assumes you are comfortable with the familiar Array.prototype methods. The goal is to choose between the two families based on how each one actually behaves.
Two Models of the Same Operations
Array.prototype.map and Iterator.prototype.map share a name and a callback shape, but they run on different execution models.
- Eager (Array methods): each step processes the whole input and returns a new, complete array. The next step starts only after the previous one finishes.
- Lazy (iterator helpers): each step returns a new iterator. Nothing runs until a consumer pulls a value. Then that single value travels through the whole chain before the next one is requested.
Seeing the Difference in Callback Order
The clearest way to see the difference is to log every callback call. Both pipelines below produce the same result, but they do different amounts of work in a different order.
const data = [1, 2, 3, 4];
const eagerLog = [];
const eager = data
.map((x) => { eagerLog.push(`map ${x}`); return x * 10; })
.filter((x) => { eagerLog.push(`filter ${x}`); return x > 15; })
.slice(0, 1);
const lazyLog = [];
const lazy = data
.values()
.map((x) => { lazyLog.push(`map ${x}`); return x * 10; })
.filter((x) => { lazyLog.push(`filter ${x}`); return x > 15; })
.take(1)
.toArray();
console.log(eager, eagerLog);
// [20] ['map 1', 'map 2', 'map 3', 'map 4',
// 'filter 10', 'filter 20', 'filter 30', 'filter 40']
console.log(lazy, lazyLog);
// [20] ['map 1', 'filter 10', 'map 2', 'filter 20']The eager version made eight callback calls and two intermediate arrays. The lazy version made four calls, created no intermediate arrays, and stopped as soon as take(1) was satisfied. This is the reason to use iterator helpers, and it also shows the main behavioral risk: if your callbacks have side effects, switching from one model to the other changes which side effects happen and in what order.
What Each Side Can Do
Iterator helpers are deliberately smaller than the Array API. An iterator has no length, no indexes, and no way to go backward. Any operation that needs those things is missing.
| Capability | Array methods | Iterator helpers |
|---|---|---|
| `map`, `filter`, `flatMap`, `reduce`, `forEach`, `some`, `every`, `find` | Yes | Yes |
| Limit or skip | `slice` (copies) | `take`, `drop` (lazy) |
| `sort`, `reverse`, `toSorted` | Yes | No |
| `at`, `indexOf`, `includes`, `findLast` | Yes | No |
| `join`, `concat` | Yes | No (`Iterator.concat` is a later addition, not in ES2025) |
| `length` known up front | Yes | No |
| Reusable after reading | Yes | No, single use |
| Infinite input | Impossible | Supported |
| Intermediate allocations | One array per step | None (one small iterator object per step) |
| Stops early on `find`/`some`/`take` | Only the final step stops early | The whole chain stops |
Note the last row. array.map(f).find(g) stops find early, but map has already run on every element. With array.values().map(f).find(g), f runs only until g matches.
Performance: Lazy Is Not Automatically Faster
Laziness saves work you would have thrown away and memory for intermediate results. It does not make each element cheaper. Every value that passes through an iterator chain costs a next() call per stage and an { value, done } result object. Engines optimize array methods on dense arrays heavily, so for a small array that you process completely, the eager chain is often as fast or faster.
Rough rules of thumb:
- Small, fully processed arrays: use Array methods. They are simpler and you won't get a meaningful benefit from laziness.
- Large inputs where you need only a prefix or the first match: use helpers. The savings grow with the amount of work you skip.
- Long chains over large arrays: helpers avoid allocating one large array per stage, which lowers peak memory and garbage-collection pressure.
- Hot loops where you have measured a problem: a plain
for...ofloop beats both. Measure before you choose.
Mixing Both: Materialize at the Boundary
Real code often needs both models. A common pattern is to filter and limit lazily, then call toArray() when you need an Array-only operation such as sorting. Sorting must see every element, so it can never be lazy. The goal is to make the array you sort as small as possible.
function* readings() {
let seed = 7;
for (let id = 0; id < 1_000_000; id++) {
seed = (seed * 48271) % 2147483647;
yield { id, ok: seed % 5 !== 0, value: seed % 1000 };
}
}
const top = readings()
.filter((r) => r.ok) // lazy: no million-item array
.take(1000) // lazy: stop after 1000 good readings
.toArray() // materialize only 1000 items
.sort((a, b) => b.value - a.value)
.slice(0, 3); // array methods from here on
console.log(top.length); // 3The generator yields up to a million objects, but no more than 1000 of them ever exist in an array at once. Generation stops once take has 1000 values, because take closes the generator.
You can cross the boundary in the other direction too. Call .values() on an array when you want lazy behavior for one part of a chain:
const words = ['alpha', 'beta', 'gamma', 'delta', 'epsilon'];
const firstLong = words
.values()
.map((w) => w.toUpperCase())
.find((w) => w.length > 4);
console.log(firstLong); // 'ALPHA'A Decision Guide
In short:
- If the data is not an array yet (a generator, a
Mapiterator, a parser yielding records), use helpers. Converting to an array first defeats the purpose. - If you need random access, ordering, length, or a second pass, you need an array. Materialize once with
toArray()and use Array methods. - If the data is an array and you process all of it, keep using Array methods.
- If the data is a large array and you stop early, use
.values()and helpers.
Exercise
A function receives a 2-million-element array of log entries and must return the first 20 entries whose level is "error", with messages trimmed. It currently uses logs.filter(isError).map(trim).slice(0, 20). What changes if you rewrite it as logs.values().filter(isError).map(trim).take(20).toArray(), and is there any reason not to?
Show answer
The eager version calls isError on all 2 million entries, builds an array of every error, trims every error, and then keeps only 20. The lazy version stops pulling once 20 trimmed errors exist, so isError runs only until the 20th error is found and trim runs exactly 20 times, with no large intermediate arrays. The result is the same. The only reason not to switch is if isError or trim has side effects that callers depend on for every entry (for example counting all errors), because those calls would no longer happen.
Exercise
You need the five highest scores from a generator that yields 10,000 score objects. Can this be written entirely with iterator helpers? Sketch a correct pipeline.
Show answer
No. Finding the highest values requires seeing every element, and iterator helpers have no sort. Materialize, then use Array methods: scores().toArray().sort((a, b) => b.score - a.score).slice(0, 5). Any lazy filtering that removes items first (for example .filter((s) => s.valid)) should go before toArray so that the array you sort is smaller.