Sub topic 3
Lazy Evaluation: Nothing Runs Until You Pull
This chapter assumes you know arrow functions, the array map and filter methods, for...of loops, and generator functions (function*). It also builds on the iteration protocol from earlier chapters: an iterator is an object with a next() method that returns { value, done }.
Iterator helpers are lazy. Calling .map() or .filter() on an iterator does not process any values. It returns a new iterator that remembers what to do. The work happens later, one value at a time, when something calls next() on the result. This chapter covers when that work runs, in what order, and what that means for your code.
Push versus pull
Array methods push. array.map(fn) runs fn on every element right away and gives you a finished array. The next method in the chain then runs over that whole array.
Iterator helpers pull. The consumer at the end of the chain asks for one value. That request travels back up the chain to the source. The source produces one value, and that value travels forward through each step until it reaches the consumer or a step discards it.
The source is never asked for more values than the consumer needs. That one property is what makes it possible to work with infinite sequences and to stop early without wasted work.
Creating a helper runs nothing
The first rule of laziness: building a pipeline does not call your callbacks.
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
// 2'created' prints first. The map callback has not run yet. It runs for the first time inside it.next(), and only for the value 1. Values 2 and 3 have not been touched. If you never call next() again, they never will be.
Generators work the same way, so a lazy source and a lazy pipeline fit together. A generator's body does not start until the first next() call:
function* source() {
console.log('source started');
yield 1;
console.log('source resumed');
yield 2;
}
const pipeline = source().map((x) => x + 100);
console.log('pipeline built');
console.log(pipeline.next().value);
console.log(pipeline.next().value);
// pipeline built
// source started
// 101
// source resumed
// 102The generator pauses at each yield until the pipeline pulls again.
One value at a time, through the whole chain
The second rule: values move through the pipeline one at a time. With arrays, every element goes through step one, then every element goes through step two. With iterator helpers, the first element goes through every step before the second element starts.
const log = [];
[1, 2, 3]
.map((x) => { log.push(`map ${x}`); return x * 10; })
.filter((x) => { log.push(`filter ${x}`); return x > 10; });
console.log(log.join(', '));
// map 1, map 2, map 3, filter 10, filter 20, filter 30
log.length = 0;
const lazy = [1, 2, 3]
.values()
.map((x) => { log.push(`map ${x}`); return x * 10; })
.filter((x) => { log.push(`filter ${x}`); return x > 10; });
console.log(log.length); // 0, nothing has run yet
console.log(lazy.next()); // { value: 20, done: false }
console.log(log.join(', '));
// map 1, filter 10, map 2, filter 20The first next() call did more than one step of work. filter rejected 10, so it pulled again from map, which pulled 2 from the array iterator. A single next() keeps pulling until it can return a value or the source is done. The value 3 is still waiting in the source.
This ordering matters whenever your callbacks have side effects such as logging, counters, or network calls. Do not write lazy code that assumes all of the map calls finish before any filter call starts.
A mental model: helpers as generators
You can model a helper as a small generator that loops over its input:
function* lazyMap(iterator, fn) {
for (const value of { [Symbol.iterator]: () => iterator }) {
yield fn(value);
}
}
function* lazyFilter(iterator, predicate) {
for (const value of { [Symbol.iterator]: () => iterator }) {
if (predicate(value)) yield value;
}
}
const result = lazyFilter(lazyMap([1, 2, 3].values(), (x) => x * 10), (x) => x > 10);
console.log([...result]); // [20, 30]Each generator pauses at yield. It resumes only when someone downstream asks for the next value. The real built-in helpers are not written this way. They also pass a counter to callbacks, forward return() to close the source, and validate arguments, and later chapters cover all three. The pull behavior is the same, though, and this model is accurate enough to predict when callbacks run.
Consequences you need to plan for
Callbacks see state at pull time
Because callbacks run later, they read variables as they are at pull time, not at creation time.
let factor = 2;
const scaled = [1, 2, 3].values().map((x) => x * factor);
factor = 10;
console.log(scaled.toArray()); // [10, 20, 30]If a pipeline depends on outside state, read that state into a const before you build the pipeline, or consume the pipeline right away.
Errors surface at pull time
An exception thrown inside a callback does not appear where you built the pipeline. It appears at whichever next(), for...of, or toArray() call reaches the bad value.
const parsed = ['1', '2', 'oops'].values().map((s) => {
const n = Number(s);
if (Number.isNaN(n)) throw new Error(`bad input: ${s}`);
return n;
});
console.log('built fine');
try {
for (const n of parsed) console.log(n);
} catch (e) {
console.log(e.message);
}
// built fine
// 1
// 2
// bad input: oopsPut your try...catch around the code that consumes the pipeline, not only around the code that builds it.
No intermediate arrays
An array chain of map and then filter over a million elements builds a million-element array after map, and then another array after filter. A lazy chain holds one value in flight at a time. Memory use depends on the length of the chain, not the size of the data. This is the main reason to reach for iterator helpers on large or unbounded inputs.
Nothing happens without a consumer
A pipeline that nothing consumes does nothing. This is a common bug when people use map for its side effects:
const ids = [1, 2, 3];
ids.values().map((id) => console.log('saving', id));
// prints nothing
ids.values().forEach((id) => console.log('saving', id));
// saving 1
// saving 2
// saving 3forEach is a consuming method. It pulls every value. Use it, or another consumer such as toArray or reduce, when you want the work to happen.
Summary of when work runs
| Action | Callbacks run? | Source advanced? |
|---|---|---|
| Calling `.map(fn)` or `.filter(fn)` | No | No |
| Calling `next()` once on the pipeline | Until one value passes or the source ends | As many times as needed |
| `for...of`, spread, or `toArray()` | For every value | To the end |
| Building a pipeline and never consuming it | Never | Never |
Exercise
What does this program print, in order? const it = [5, 6, 7, 8].values() .filter((n) => { console.log('f', n); return n % 2 === 0; }) .map((n) => { console.log('m', n); return n / 2; }); console.log('start'); console.log(it.next().value); console.log(it.next().value);
Show answer
It prints "start", then "f 5", "f 6", "m 6", "3", then "f 7", "f 8", "m 8", "4". Building the pipeline runs nothing. The first next() pulls 5, which filter rejects, then pulls 6, which passes and is mapped to 3. The second next() pulls 7, which is rejected, then pulls 8, which is mapped to 4.
Exercise
A colleague writes const doubled = data.values().map((x) => x * multiplier); and then sets multiplier = 0 before calling doubled.toArray(). They expected the old multiplier to be used. Why is the result all zeros, and what are two ways to fix it?
Show answer
The map callback runs during toArray(), not when map() is called, so it reads multiplier as it is at pull time, which is 0. One fix is to copy the value into a const before building the pipeline, for example const m = multiplier; and then use m in the callback. The other fix is to consume the pipeline, for example with toArray(), before multiplier changes.