Skip to main content

Harshal V. LADHE

Iterator Helpers: Lazy Pipelines over Any Iterator

Map, filter and take over any iterator, lazily.
Published at:
Last updated:
Estimated reading time:10 min read
Cover for 'Iterator Helpers: Lazy Pipelines over Any Iterator', showing numbers flowing through filter, map and take to the result [4, 16](opens full-size image in a new tab)
An endless generator through filter, map and take(2) to [4, 16], with less work than arrays and the source closed.

Introduction

Arrays have had map(), filter() and reduce() for years. Everything else that produces values one at a time, such as a Set, a Map, a generator or the result of matchAll(), didn't. To use those methods, you first copied the values into an array with [...iterable] or Array.from(), even when you only needed the first few.

Iterator helpers, added in ES2025, put the same kind of methods on iterators themselves. The important difference from arrays is that they are lazy. A pipeline does no work until something asks it for a value, and then it does only the work needed to produce that one value. That makes it safe to run a pipeline over a sequence that never ends, and cheap to stop after the first few results.

A Quick Refresher on Iterators

An iterator is an object with a next() method. Each call returns { value, done }, and done: true means there are no more values. An iterable is anything with a [Symbol.iterator]() method that returns an iterator, which is what for...of and the spread syntax look for.

const iterator = ["a", "b"].values();

iterator.next(); // { value: "a", done: false }
iterator.next(); // { value: "b", done: false }
iterator.next(); // { value: undefined, done: true }

The built-in iterators all inherit from Iterator.prototype, which is where the helpers live. That includes array.values(), set.values(), map.entries() and the other Map and Set iterators, generator objects, and string.matchAll(regex).

An array itself is iterable, but it isn't an iterator, so [1, 2, 3].take(2) throws a TypeError. Call .values() first to get an iterator over it.

Basic Usage

const prices = new Map([
  ["lamp", 40],
  ["pen", 12],
  ["desk", 250],
  ["chair", 120]
]);

const expensive = prices
  .entries()
  .filter(([, price]) => price > 100)
  .map(([name]) => name)
  .toArray();

console.log(expensive); // ["desk", "chair"]

Nothing here creates an array until the last step. filter() and map() each return a new iterator wrapped around the one before it, and toArray() pulls every value through the chain and collects the results. The same works on regex matches:

const total = "a1b22c3"
  .matchAll(/\d+/g)
  .map((match) => Number(match[0]))
  .reduce((sum, n) => sum + n, 0);

console.log(total); // 26

The Methods

The lazy helpers return a new iterator and run nothing yet. The consuming ones pull values straight away and return a plain result.

MethodReturnsRunsWhat it does
map(fn)IteratorLazilyPasses each value through fn
filter(fn)IteratorLazilyKeeps the values for which fn returns something truthy
take(n)IteratorLazilyYields at most n values, then stops
drop(n)IteratorLazilySkips the first n values, then yields the rest
flatMap(fn)IteratorLazilyYields each value of the iterable fn returns
reduce(fn, initial)Any valueAt onceCombines every value into one
toArray()ArrayAt onceCollects every value into an array
forEach(fn)undefinedAt onceCalls fn for every value
some(fn)BooleanAt oncetrue as soon as fn returns something truthy
every(fn)BooleanAt oncefalse as soon as fn returns something falsy
find(fn)Value or undefinedAt onceThe first value for which fn returns something truthy
Iterator.from(obj)IteratorLazilyGives an iterable or plain iterator object the helpers

Callbacks receive the value and a counter, starting at 0, of values seen so far. There's no third "whole collection" argument as there is with arrays, because an iterator doesn't have one.

Arguments are checked as soon as you call a method, even a lazy one: map(5) throws a TypeError and take(-1) throws a RangeError straight away, not when the first value is pulled.

When Each Step Runs

An array pipeline runs one step at a time over the whole collection. filter() goes through every element and builds a new array, then map() goes through that array and builds another. An iterator pipeline runs one value at a time through every step. Logging from each callback shows the difference:

function* naturals() {
  let n = 1;
  while (true) yield n++;
}

const result = naturals()
  .filter((n) => { console.log("filter", n); return n % 2 === 0; })
  .map((n) => { console.log("map", n); return n * n; })
  .take(2)
  .toArray();

// filter 1
// filter 2
// map 2
// filter 3
// filter 4
// map 4

console.log(result); // [4, 16]

map() runs straight after filter() lets a value through, and the work ends as soon as take(2) has two results. The same steps on an array of the first six numbers run filter() six times and map() three times, and then slice(0, 2) throws one of those results away.

Until something pulls on it, a pipeline is only a description of work, and no callback has run. Values are pulled by next(), for...of, the spread syntax, Array.from() and the consuming helpers. So a map() with side effects does nothing if nothing reads it: use forEach() when the side effect is the point.

Infinite Sequences

Because nothing runs ahead of what's asked for, a pipeline can start from a sequence that never ends, as long as something limits how much of it you read. take() is the usual limit:

function* fibonacci() {
  let [a, b] = [0, 1];
  while (true) {
    yield a;
    [a, b] = [b, a + b];
  }
}

const firstEvenFibs = fibonacci()
  .filter((n) => n % 2 === 0)
  .take(5)
  .toArray();

console.log(firstEvenFibs); // [0, 2, 8, 34, 144]

fibonacci().find((n) => n > 1000); // 1597

find(), some() and every() also stop by themselves once they know the answer, so they're safe on an infinite sequence as long as an answer exists. For a reusable version of the filter().take() pattern, see First N Matches from Any Iterable with filter() and take().

drop() combines with take() to read a window from the middle, such as one page of results:

const page = (iterator, pageNumber, pageSize) =>
  iterator.drop((pageNumber - 1) * pageSize).take(pageSize).toArray();

page(naturals(), 3, 5); // [11, 12, 13, 14, 15]

drop(10) still reads and discards ten values from the source: it can't jump over them the way slice() jumps to an array index.

Stopping Early and Closing Iterators

Some iterators hold a resource, such as a generator with a finally block that tidies up. An iterator is told "I'm finished with you" through its optional return() method, and generators run their finally block when it's called.

The helpers call return() on the iterator they wrap whenever they stop before it's exhausted: take(n) when it's asked for a value after the nth, find(), some() and every() once they have an answer, and any helper whose callback throws. Leaving a for...of loop early does the same.

function* readLines() {
  console.log("open");
  try {
    let line = 1;
    while (true) yield `line ${line++}`;
  } finally {
    console.log("close");
  }
}

for (const line of readLines().take(2)) {
  console.log(line);
}

// open
// line 1
// line 2
// close

The source never produced a third line. When the loop asked for one, take(2) called return() on the generator instead of reading further, which ran the finally block.

That timing matters if you drive the iterator by hand. After two next() calls on take(2), the source is still open. It's closed by a third next() call, or by calling return() yourself. If you abandon a half-read iterator without either, its finally block never runs.

Wrapping Your Own Iterators with Iterator.from()

An iterator you write by hand, or one from a library, is usually a plain object with a next() method. It doesn't inherit from Iterator.prototype, so it has no helpers. Iterator.from() wraps it in one that does:

function countdown(from) {
  let current = from;
  return {
    next() {
      return current > 0
        ? { value: current--, done: false }
        : { value: undefined, done: true };
    }
  };
}

Iterator.from(countdown(3)).map((n) => n * 10).toArray(); // [30, 20, 10]

It also accepts any iterable, such as a Set or a string, and returns an iterator that already has the helpers unchanged, so Iterator.from(array.values()) costs nothing. The wrapper passes return() calls through, so a hand-written iterator with a return() method is closed by take() just like a generator. For a class you control, class Countdown extends Iterator gives every instance the helpers without wrapping.

One-Shot Iterators

An array can be read as many times as you like. An iterator can be read once. Every value it hands out is gone, and once it's done it stays done:

const evens = [1, 2, 3, 4].values().filter((n) => n % 2 === 0);

console.log([...evens]); // [2, 4]
console.log([...evens]); // []: already used up

No error tells you this happened. If you need the values more than once, collect them with toArray() and reuse the array, or keep a function that builds a fresh pipeline each time:

const numbers = [1, 2, 3, 4];
const evens = () => numbers.values().filter((n) => n % 2 === 0);

console.log(evens().toArray()); // [2, 4]
console.log(evens().toArray()); // [2, 4]

Iterator Helpers vs Array Methods

The method names match on purpose, but the two are not interchangeable.

Array methodsIterator helpers
Works onArraysAny iterator: Set, Map, generators, matchAll(), your own
EvaluationEach step runs over the whole array firstEach value runs through every step in turn
Intermediate resultsA new array per stepNone until toArray()
Infinite sourcesNot possibleFine with take(), find(), some() or every()
Reading it againAs often as you likeOnce only
length, sort(), slice(), at()YesNo: collect with toArray() first
Callback arguments(value, index, array)(value, counter)

Try It Live

Run lazy logs each value going through filter(), map() and take() and the source closing. Run eager runs the same steps as array methods, so you can compare the work. Pull one value calls next() once.

Lazy Iterator Pipeline vs Eager Arrays

Run filter(), map() and take() lazily over an endless source and watch each value travel down the chain and the source close, then run the same steps as array methods and compare values read, callback calls and arrays created, or pull one value at a time with next().

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Iterator Helpers Playground</title>
  </head>
  <body>
    <main class="playground">
      <header class="playground-header">
        <h1>Lazy Iterator Pipeline vs Eager Arrays</h1>
        <p>One pipeline, <code>filter()</code> then <code>map()</code> then <code>take()</code>, over the natural numbers. Run it lazily with iterator helpers on an endless source, or eagerly with array methods on the first 30 numbers, and compare what each step had to touch.</p>
      </header>

      <p class="tip" id="support-tip" hidden>Your browser doesn't support iterator helpers, so the lazy buttons are disabled. They're supported in Chrome and Edge 122, Firefox 131, Safari 18.4 and Node 22 or later. The eager array version still works.</p>

      <fieldset class="control-group">
        <legend>Pipeline</legend>
        <div class="fields-grid fields-grid--3">
          <div class="field">
            <label for="filter-select">filter()</label>
            <select id="filter-select">
              <option value="even">Even numbers</option>
              <option value="three">Multiples of 3</option>
              <option value="seven">Multiples of 7</option>
            </select>
          </div>
          <div class="field">
            <label for="map-select">map()</label>
            <select id="map-select">
              <option value="square">Square it</option>
              <option value="ten">Times 10</option>
            </select>
          </div>
          <div class="field">
            <label for="take-input">take()</label>
            <input type="number" id="take-input" min="1" max="8" value="3">
          </div>
        </div>
        <pre class="code" id="code"></pre>
      </fieldset>

      <fieldset class="control-group">
        <legend>Run it</legend>
        <div class="actions">
          <button type="button" class="toggle-btn" id="lazy-btn">Run lazy (iterator)</button>
          <button type="button" class="secondary-btn" id="eager-btn">Run eager (array)</button>
          <button type="button" class="secondary-btn" id="step-btn">Pull one value</button>
          <button type="button" class="secondary-btn" id="reset-btn">Reset</button>
        </div>
      </fieldset>

      <section class="demo-area" aria-label="Pipeline results">
        <dl class="stats">
          <div><dt>Read from source</dt><dd id="stat-pulled">0</dd></div>
          <div><dt>filter() calls</dt><dd id="stat-filter">0</dd></div>
          <div><dt>map() calls</dt><dd id="stat-map">0</dd></div>
          <div><dt>Arrays created</dt><dd id="stat-arrays">0</dd></div>
          <div><dt>Source closed</dt><dd id="stat-closed">no</dd></div>
        </dl>
        <ul class="results" id="results"></ul>
        <p class="empty" id="empty">No results yet.</p>
      </section>

      <output class="readout" id="readout" aria-live="polite">Press a button to start.</output>
    </main>

    <script src="./index.js"></script>
  </body>
</html>

Read-only
Ln –, Col –HTML3.1 KBUTF-8

Starting sandbox…

No console output yet.

Browser Support and Fallbacks

Iterator helpers are supported in Chrome and Edge 122, Firefox 131, Safari 18.4 and Node 22. Detect the feature rather than the browser:

const hasIteratorHelpers =
  typeof Iterator === "function" && typeof Iterator.prototype.take === "function";

For older environments, a polyfill such as core-js adds the global Iterator and all of its helpers, so the rest of your code stays the same:

import "core-js/actual/iterator";

Common Pitfalls

1. Forgetting to Limit an Infinite Source

naturals().map(fn).toArray() never returns, and neither does forEach(), reduce() or every() on an endless sequence where the answer never turns up. Put a take() before any step that reads everything.

2. Returning a String from flatMap()

flatMap() flattens an array or other iterable object, but it rejects a string with a TypeError, so a word isn't silently split into letters. Return [...word] if splitting into characters is what you want.

Where Should You Use This?

  • Filtering or transforming a Set or Map without copying it into an array first
  • Taking the first few matches from a large collection or a long matchAll() result
  • Generators that produce an unbounded sequence, such as IDs, retry delays or simulation steps
  • Library code that accepts "any iterable" and shouldn't force callers to build arrays

Reach for an array instead when the data is small and already an array, or when you need to sort, index, measure the length or read it more than once.

Frequently Asked Questions

Key Takeaway

Iterator helpers give every iterator the map(), filter() and reduce() family arrays already had, plus take() and drop(). They are lazy: each value flows through every step before the next one is read, so a pipeline can start from an infinite sequence and stop as soon as it has enough, closing the source as it goes. An iterator can be read only once and has no length or index, so reach for an array when you need those.

Changelog

  • — Initial publication.
This tutorial is licensed under CC BY 4.0 by the author.

Share this tutorial

Spotted a mistake or something outdated in this tutorial? Suggest a correction.