Course contentsShow
← JavaScript
Lesson 2052 of 2,72342. Iteration Protocols Deep DiveFree lesson

Lazy Map and Filter

Building custom lazy map/filter iterators that transform without creating intermediate arrays.

Lazy Map and Filter

You'll learn how to write custom lazy map and filter iterators that transform data on-demand without creating intermediate arrays.

The Problem with Eager Operations

Array's built-in map() and filter() are eager—they process every element immediately and return a new array. If you chain them, each step creates a full intermediate array:

const result = [1, 2, 3, 4, 5]
  .map(x => x * 2)    // Creates [2, 4, 6, 8, 10]
  .filter(x => x > 5); // Creates [6, 8, 10]

That's wasteful if you're working with large datasets or only need a few values.

Building Lazy Transformations

Lazy iterators perform transformations one value at a time as you request them:

function* lazyMap(iterable, fn) {
  for (const value of iterable) {
    yield fn(value);
  }
}

function* lazyFilter(iterable, predicate) {
  for (const value of iterable) {
    if (predicate(value)) {
      yield value;
    }
  }
}

Now chain them without intermediate arrays:

const numbers = [1, 2, 3, 4, 5];
const transformed = lazyFilter(
  lazyMap(numbers, x => x * 2),
  x => x > 5
);

for (const n of transformed) {
  console.log(n); // 6, 8, 10 — computed on-the-fly
}

Why This Matters

Each value flows through the entire pipeline before the next value starts processing. No temporary arrays. Perfect for infinite sequences or when you need early termination:

// Only processes until we find 2 results
let count = 0;
for (const n of transformed) {
  console.log(n);
  if (++count === 2) break; // Only computed 2 * 2 and 3 * 2 so far!
}

Key Takeaway: Lazy map and filter iterators transform values on-demand using generators, avoiding intermediate arrays and enabling efficient processing of large or infinite sequences.