Sub topic 3
Lazy Evaluation: Nothing Runs Until You Pull
This chapter assumes you know the iteration protocol: an iterator has a next() method that returns { value, done }. It also assumes you know that iterator helpers live on Iterator.prototype. Both topics were covered in the previous two chapters.
Eager versus lazy
Array methods are eager. A call like array.map(fn) runs fn on every element right away and returns a new, complete array.
Iterator helpers are lazy. A call like iterator.map(fn) runs nothing. It returns a new iterator that remembers two things: its source and fn. The callback runs only when something calls next() on that new iterator. This model is called pull-based iteration because the consumer pulls values one at a time, and each pull travels back up the chain to the source.
const it = [1, 2, 3].values().map((x) => {
console.log('mapping', x);
return x * 2;
});
console.log('created');
console.log(it.next().value);
// created
// mapping 1
// 2created prints first. When the helper is built, map has not touched the array. Only the first next() call runs the callback, and it runs once, for one element.
One value at a time through the whole chain
When you chain helpers, values move through the chain one at a time. With arrays, every element finishes one stage before the next stage starts. With iterators, each value goes through every stage before the next value is read from the source.
const it = [1, 2, 3, 4]
.values()
.filter((n) => {
console.log('filter', n);
return n % 2 === 0;
})
.map((n) => {
console.log('map', n);
return n * 10;
});
console.log('built');
console.log(it.next().value);
console.log(it.next().value);
// built
// filter 1
// filter 2
// map 2
// 20
// filter 3
// filter 4
// map 4
// 40The first next() asks map for a value. map asks filter, and filter keeps pulling from the array until a value passes the test. The value 1 fails, so map never sees it.
Why laziness matters
| Concern | Eager arrays | Lazy iterator helpers |
|---|---|---|
| When callbacks run | Immediately, for all elements | On each `next()` call |
| Intermediate storage | A full array per stage | None |
| Infinite sources | Never finish | Work if you stop pulling |
| Unused values | Still computed | Never computed |
Exercise
What does this code print, and in what order? const it = [5, 6, 7].values().map((x) => { console.log('see', x); return x + 1; }); console.log('start'); it.next(); console.log('end');
Show answer
It prints "start", then "see 5", then "end". Building the helper runs no callback. The single next() call pulls one value, so the callback runs only for 5. The values 6 and 7 are never mapped.
Exercise
In the filter-then-map example, how many times does the filter callback run before the first value reaches the consumer, and why?
Show answer
Twice. filter pulls 1, rejects it, then pulls 2, which passes and goes on to map. The filter keeps pulling until it finds a matching value or the source runs out.