Sub topic 15
Lazy Sequences with Generators
This chapter assumes you know higher-order functions and closures from earlier chapters, and that you are comfortable with for...of loops and spread syntax. You will see how generators let you describe a sequence, even an infinite one, and compute only the values you ask for.
Eager vs. lazy evaluation
Array methods such as map and filter are eager. Each call walks the whole array and builds a new array before the next step runs. A chain like .map().filter() over a million items creates a million-element array between the two steps, even if you only need the first three results.
Lazy evaluation does the opposite. It defers each computation until someone asks for a value. In JavaScript, the built-in tool for this is the generator function.
Generator basics
A generator function is declared with function*. Calling it does not run its body. It returns an iterator, an object with a next() method. Each next() call runs the body until the next yield, hands back that value, and pauses there.
function* countTo(limit) {
for (let i = 1; i <= limit; i++) {
console.log(`producing ${i}`);
yield i;
}
}
const it = countTo(3);
console.log(it.next()); // producing 1, then { value: 1, done: false }
console.log(it.next()); // producing 2, then { value: 2, done: false }Nothing is logged until next() is called. That pause-and-resume behavior is what makes lazy pipelines possible.
Building a lazy pipeline
Because generators accept any iterable and produce an iterable, you can write small, pure-looking transformers and chain them together the way you chain array methods:
function* naturals() {
let n = 1;
while (true) yield n++;
}
function* mapIter(fn, iterable) {
for (const x of iterable) yield fn(x);
}
function* take(count, iterable) {
if (count <= 0) return;
for (const x of iterable) {
yield x;
if (--count <= 0) return;
}
}
console.log([...take(3, mapIter((x) => x * x, naturals()))]); // [ 1, 4, 9 ]naturals() never ends, but the program finishes. The spread operator pulls values from take, take pulls from mapIter, and mapIter pulls from naturals. When take returns after three values, the whole chain stops. Exactly three numbers are generated and squared.
Common mistakes
| Mistake | What happens | Fix |
|---|---|---|
| `[...naturals()]` | Infinite loop, the process hangs or runs out of memory | Always bound infinite sources with `take` or similar |
| Reusing a generator object | The second loop sees nothing, because the iterator is already exhausted | Call the generator function again to get a fresh iterator |
| Checking the count before `yield` in `take` | One extra value is pulled from upstream | Yield first, then decrement and return |
| Side effects inside a lazy step | Effects run later, or never, depending on consumption | Keep transformer functions pure |
When to choose laziness
Reach for generators when the data is large, infinite, or expensive to produce, such as paginated API results, file lines, or simulations, and you usually need only part of it. For small arrays, eager array methods are simpler to read and debug, and they are often faster.
Exercise
Write a generator filterIter(pred, iterable) and use it with naturals, mapIter, and take to get the first three even squares.
Show answer
function filterIter(pred, iterable) { for (const x of iterable) if (pred(x)) yield x; } — then [...take(3, filterIter((x) => x % 2 === 0, mapIter((x) => x x, naturals())))] returns [ 4, 16, 36 ].
Exercise
Given const g = take(2, naturals()), what do console.log([...g]) and a second console.log([...g]) print, and why?
Show answer
The first prints [ 1, 2 ] and the second prints [ ]. A generator object is a single-use iterator, and the first spread exhausts it.