Sub topic 15
Lazy Sequences with Generators
This chapter assumes you can read generator syntax (function* and yield), know how for...of works, and remember the pipe helper from the chapter on composition. All examples run in Node.js 18 or later, except the section on built-in iterator helpers, which needs Node.js 22 or later.
Eager vs. Lazy Evaluation
Array methods are eager. Each call to map or filter walks the whole array and builds a new array before the next step starts. That works well for small, finite data. It wastes work when you only need the first few results, and it cannot handle data that has no end.
Lazy evaluation computes a value only when a consumer asks for it. In JavaScript, generators give you laziness without any library. The trace below shows how much work eager evaluation does when the code only needs one result:
const log = [];
const firstBig = [1, 2, 3, 4, 5]
.map((x) => { log.push(`map ${x}`); return x * 10; })
.filter((x) => { log.push(`filter ${x}`); return x > 15; })[0];
console.log(firstBig); // 20
console.log(log.length); // 10: every element was mapped and filteredThe code only needed the value 20, but it did ten units of work to get it.
The Iterator Protocol in One Paragraph
An iterator is an object with a next() method that returns { value, done }. An iterable is an object with a [Symbol.iterator]() method that returns an iterator. Calling a generator function runs none of its body. It returns a generator object, which is both an iterator and an iterable. Each next() call runs the body until the next yield and then pauses. Values are pulled by the consumer, one at a time, which is what makes generators lazy.
function* threeSteps() {
console.log('start');
yield 1;
console.log('middle');
yield 2;
}
const it = threeSteps(); // nothing printed yet
console.log(it.next()); // start, then { value: 1, done: false }
console.log(it.next()); // middle, then { value: 2, done: false }
console.log(it.next()); // { value: undefined, done: true }Building Lazy Operators
To fit the functional style of earlier chapters, write each operator as a curried function. It takes its configuration first and returns a generator function that takes the iterable last. That shape plugs directly into pipe.
const pipe = (...fns) => (x) => fns.reduce((acc, fn) => fn(acc), x);
function* naturals() {
let n = 1;
while (true) yield n++;
}
const map = (fn) => function* (iterable) {
for (const x of iterable) yield fn(x);
};
const filter = (pred) => function* (iterable) {
for (const x of iterable) if (pred(x)) yield x;
};
const take = (n) => function* (iterable) {
if (n <= 0) return;
let remaining = n; // local copy, so take(n) is reusable
for (const x of iterable) {
yield x;
if (--remaining <= 0) return;
}
};
const firstThreeEvenSquares = pipe(
map((x) => x * x),
filter((x) => x % 2 === 0),
take(3)
);
console.log([...firstThreeEvenSquares(naturals())]); // [ 4, 16, 36 ]naturals() never ends, yet the program finishes. The spread operator pulls from take. take pulls from filter, filter pulls from map, and map pulls from naturals. Once take has three values it returns, and nothing more is requested.
Now rerun the earlier trace lazily. The steps interleave per element, and the work stops at the first match:
const pipe = (...fns) => (x) => fns.reduce((acc, fn) => fn(acc), x);
const map = (fn) => function* (it) { for (const x of it) yield fn(x); };
const filter = (p) => function* (it) { for (const x of it) if (p(x)) yield x; };
const log = [];
const lazy = pipe(
map((x) => { log.push(`map ${x}`); return x * 10; }),
filter((x) => { log.push(`filter ${x}`); return x > 15; })
)([1, 2, 3, 4, 5]);
console.log(lazy.next().value); // 20
console.log(log); // [ 'map 1', 'filter 10', 'map 2', 'filter 20' ]Gotchas and Failure Modes
Generator Objects Are One-Shot
A generator object stays exhausted after it is consumed. A second pass silently yields nothing, and that bug is easy to miss.
function* squaresOf(xs) { for (const x of xs) yield x * x; }
const squares = squaresOf([1, 2, 3]);
console.log([...squares]); // [ 1, 4, 9 ]
console.log([...squares]); // [] (already exhausted)
// Fix: expose a reusable iterable that creates a fresh generator per pass
const reusableSquares = (xs) => ({
*[Symbol.iterator]() { for (const x of xs) yield x * x; }
});
const sq = reusableSquares([1, 2, 3]);
console.log([...sq], [...sq]); // [ 1, 4, 9 ] [ 1, 4, 9 ]Infinite Sequences Need a Limit Before Any Eager Step
[...naturals()], Array.from(naturals()), or a reduce over an infinite source never returns. The process hangs and eventually runs out of memory. Put take (or a takeWhile) before anything that consumes everything. Order matters for correctness as well: take(3) followed by filter(isEven) gives at most three values, which is a different result from filter(isEven) followed by take(3).
Side Effects Run at Consumption Time
A lazy pipeline does nothing when you build it. Any logging, network calls, or mutation inside map runs later, possibly never, and possibly more than once if you rebuild the pipeline. This is one more reason to keep the functions you pass in pure, as the chapters on pure functions and side effects recommend.
Early Exit and Cleanup
When a for...of loop exits early through break, return, or a thrown error, it calls the iterator's return() method. That runs any finally block in the generator, so you can release resources such as file handles. Our take relies on this behavior: its return exits the inner loop, which closes the upstream generators.
function* counter() {
try {
let i = 0;
while (true) yield i++;
} finally {
console.log('cleanup ran');
}
}
for (const x of counter()) {
if (x === 2) break; // triggers return(), so "cleanup ran" is printed
}If you call next() by hand and abandon the iterator, finally never runs. Prefer for...of or call it.return() yourself.
Built-in Iterator Helpers
ES2025 adds methods to Iterator.prototype, and every generator object inherits them. On Node.js 22 or later and current browsers you can write the pipeline without your own operators:
function* naturals() {
let n = 1;
while (true) yield n++;
}
const result = naturals()
.map((x) => x * x)
.filter((x) => x % 2 === 0)
.take(3)
.toArray();
console.log(result); // [ 4, 16, 36 ]The helpers also include drop, flatMap, reduce, some, every, find, and forEach. They only exist on iterators, so plain arrays need array.values() first. Use Iterator.from(obj) to wrap any other iterable.
When to Choose Lazy Sequences
| Situation | Eager arrays | Lazy generators |
|---|---|---|
| Small, finite data used in full | Simpler, usually faster | Extra per-item overhead |
| Only the first few results needed | Computes everything | Stops early |
| Infinite or unbounded source | Impossible | Natural fit |
| Large data, memory-bound | Holds every intermediate array | Holds one item at a time |
| Need random access or `length` | Built in | Must materialize first |
| Iterate more than once | Free | Needs a reusable iterable |
Exercises
Exercise
Write a curried lazy operator takeWhile(pred) that yields values from an iterable until pred first returns false, and then stops. Use it with naturals() and pipe to collect all squares less than 50.
Show answer
const takeWhile = (pred) => function (iterable) { for (const x of iterable) { if (!pred(x)) return; yield x; } }; then [...pipe(map((x) => x x), takeWhile((x) => x < 50))(naturals())] gives [1, 4, 9, 16, 25, 36, 49]. The early return ends the for...of loop, which closes the upstream generators.
Exercise
A teammate writes const evens = filter((x) => x % 2 === 0)([1, 2, 3, 4]); console.log([...evens].length); console.log([...evens][0]); and expects to see 2 and then 2. What prints, and how would you fix it?
Show answer
It prints 2 and then undefined. evens is a generator object, and the first spread exhausts it, so the second spread produces an empty array. Fix it by materializing once (const arr = [...evens]) or by returning a reusable iterable whose [Symbol.iterator] creates a fresh generator on each pass.
Exercise
Why does pipe(take(3), filter(isEven)) produce a different result than pipe(filter(isEven), take(3)) on naturals()? Which of the two could hang if take were removed?
Show answer
The first takes 1, 2, 3 and then filters them, giving [2]. The second filters first and stops after three even numbers, giving [2, 4, 6]. Without take, both pipelines run over an infinite source, so spreading either one would hang.