Skip to content
FEE
Frontend Engineering Essentials
Senior Level
Hardened· 2026-07

[FEE-10100] Iterator Helpers — .map(), .filter(), .take() on Iterators ​

INFO

You can now chain .map(), .filter(), and .take() directly on any iterator, including generators and Sets, without first spreading into an array.

Web Platform Proposals

This proposal reached TC39 Stage 4 and shipped as part of ECMAScript 2025. Available in Chrome 122+, Firefox 131+, Safari 18.4+. Iterator helpers are Baseline Newly Available as of March 2025. Check MDN for the current compatibility table.

Context ​

JavaScript has always had a composition problem with iterables. Arrays have rich transformation methods: .map(), .filter(), .reduce(). Those methods only work on arrays. Any other iterable (a Set, a Map, a generator, a NodeList) must first be materialized into an array before you can do anything useful with it.

The four problems ​

1. Forced eager materialization. If you have a Set of user IDs and you want to map over it, you cannot call .map() directly. You must spread it first:

js
const ids = new Set([1, 2, 3, 4, 5]);

// This does NOT work — Set has no .map()
ids.map(id => fetchUser(id)); // TypeError

// You must materialize first
[...ids].map(id => fetchUser(id));

That spread creates a full intermediate array, even if you only needed the first result.

2. Intermediate arrays multiply. Chaining .filter() and .map() on an array creates two separate intermediate arrays. For large datasets this is wasteful:

js
const result = largeArray
  .filter(x => x.active)   // intermediate array #1
  .map(x => x.name)        // intermediate array #2
  .slice(0, 10);            // final result

Three passes over the data. Three allocations. The .slice(0, 10) at the end makes all the work done on items 11 through N completely wasted.

3. Generators have no composition utilities. Generator functions are a powerful tool for expressing lazy sequences, but the iterator protocol they implement has no built-in helpers. A generator that yields 10,000 items has no .filter(), no .take(), nothing:

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

// To get the first 5 even numbers, you must write the loop by hand
function firstFiveEvens() {
  const result = [];
  for (const n of naturals()) {
    if (n % 2 === 0) result.push(n);
    if (result.length === 5) break;
  }
  return result;
}

Every generator that needs an early exit gets this loop written out by hand, and re-reviewed each time it appears. Libraries like Lodash and Ramda have filled this gap for arrays. _.chain() in Lodash is a well-known workaround, but it requires a runtime dependency and operates on arrays, not iterators.

4. Infinite sequences are impractical. Because there is no way to say "stop after 5 results", a developer with an infinite generator is forced to either collect into a big finite array manually, or write the early-exit loop from scratch every time.

Iterator helpers solve all four problems in one go.

A worked case: paginated records ​

Your team receives large paginated datasets from an API. Rather than pulling all pages at once, a senior engineer has written an async generator that yields records lazily as they arrive:

js
async function* fetchRecords(endpoint) {
  let cursor = null;
  do {
    const resp = await fetch(`${endpoint}?cursor=${cursor ?? ''}`);
    const page = await resp.json();
    for (const record of page.items) yield record;
    cursor = page.nextCursor;
  } while (cursor);
}

You need the first 10 active premium users from this stream. Iterator.from() only accepts synchronous iterables, and fetchRecords is an async function*, so Iterator.from(fetchRecords('/users')) cannot be used here. Iterator.from() treats whatever next() returns as an already-resolved { done, value } result; for an async generator, next() actually returns a Promise, so value reads as undefined and the first call to the .filter() predicate throws TypeError: Cannot read properties of undefined (reading 'active').

The proposal that would let you write a clean chain against an async source, AsyncIterator helpers, is a separate TC39 proposal. As of mid-2026 it is at Stage 2, is not part of ES2025, and has not shipped in any browser (see Browser Support & Version Reference). Until it ships, an async source still needs a manual loop with an early exit:

js
const result = [];
for await (const r of fetchRecords('/users')) {
  if (r.active && r.plan === 'premium') result.push(r);
  if (result.length === 10) break;
}

Iterator helpers do solve this exact problem today for a synchronous source, for example a generator over records already loaded in memory. Example 1 below runs the same filter-then-cap chain end to end.

Visual ​

The eager path creates three intermediate arrays regardless of how few results you need. The lazy path pulls values one at a time. Once .take(5) has collected 5 items, the generator is never called again.

Example ​

1. Filtering and capping a synchronous record stream ​

js
function* cachedRecords() {
  yield { id: 1, active: true, plan: 'premium' };
  yield { id: 2, active: false, plan: 'premium' };
  yield { id: 3, active: true, plan: 'free' };
  yield { id: 4, active: true, plan: 'premium' };
  yield { id: 5, active: true, plan: 'premium' };
  // a real dataset would keep yielding further records
}

const result = Iterator.from(cachedRecords())
  .filter(r => r.active && r.plan === 'premium')
  .take(10)
  .toArray();

console.log(result);
// [{ id: 1, active: true, plan: 'premium' },
//  { id: 4, active: true, plan: 'premium' },
//  { id: 5, active: true, plan: 'premium' }]

This is the filter-then-cap chain from Context, running against a synchronous generator. .take(10) stops the chain once it has collected 10 matches or the generator is exhausted, whichever happens first. The equivalent chain for an asynchronous source such as fetchRecords is not available today; see Context and Browser Support & Version Reference.

2. Infinite Fibonacci with lazy filtering ​

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

// First 5 even Fibonacci numbers
const result = Iterator.from(fibonacci())
  .filter(n => n % 2 === 0)
  .take(5)
  .toArray();

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

The generator yields values indefinitely; .take(5) ensures it stops after collecting 5 even numbers.

3. Deduplicating and transforming with Iterator.from(Set) ​

js
const raw = new Set([1, 2, 3, 2, 1, 4, 5]);

const doubled = Iterator.from(raw)
  .map(x => x * 2)
  .toArray();

console.log(doubled); // [2, 4, 6, 8, 10]

Iterator.from() wraps the Set, which already deduplicates by construction, and gives it the full iterator helper API.

4. Mapping over a Map's entries ​

js
const scores = new Map([
  ['Alice', 92],
  ['Bob', 78],
  ['Carol', 85],
]);

const passing = Iterator.from(scores)
  .filter(([, score]) => score >= 80)
  .map(([name, score]) => `${name}: ${score}`)
  .toArray();

console.log(passing); // ["Alice: 92", "Carol: 85"]

5. Lodash equivalent for comparison ​

The Lodash _.chain() pattern compared side by side:

js
// Lodash — array-based, requires a dependency
import _ from 'lodash';

const lodashResult = _.chain([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
  .filter(n => n % 2 === 0)
  .map(n => n * n)
  .take(3)
  .value();
// [4, 16, 36]

// Iterator helpers — native, works on any iterable
function* nums() { let n = 1; while (true) yield n++; }

const nativeResult = Iterator.from(nums())
  .filter(n => n % 2 === 0)
  .map(n => n * n)
  .take(3)
  .toArray();
// [4, 16, 36]

The iterator helpers version works on an infinite generator; the Lodash version requires a finite array upfront.

6. Early exit with .find() and .some() ​

js
const data = Iterator.from([10, 3, 7, 25, 2, 18]);

// Short-circuits on first match — does not consume the whole iterator
const firstBig = data.find(n => n > 20);
console.log(firstBig); // 25

// Check existence without collecting
const hasTiny = Iterator.from([10, 3, 7, 25]).some(n => n < 5);
console.log(hasTiny); // true

Best Practices ​

Engineers SHOULD chain iterator helpers before any eager terminal to avoid intermediate arrays. The lazy helpers (.map(), .filter(), .take(), .drop(), .flatMap()) return new iterator objects. No work is done until a terminal method consumes the chain.

js
// Correct: all transformation is lazy, one terminal at the end
const result = Iterator.from(data)
  .filter(x => x.active)
  .map(x => x.name)
  .take(10)
  .toArray();

// Incorrect: .toArray() in the middle breaks laziness
const names = Iterator.from(data)
  .filter(x => x.active)
  .toArray()             // eager — materializes here
  .map(x => x.name)     // now operating on an Array, not an iterator
  .slice(0, 10);

Engineers MUST use Iterator.from() to access helpers on non-Array iterables. Set, Map, generator results, and NodeList do not inherit from Iterator.prototype directly. Wrap them with Iterator.from() first:

js
const set = new Set([1, 2, 3, 4, 5]);

// TypeError — Set.prototype has no .filter()
set.filter(x => x > 2);

// Correct
Iterator.from(set).filter(x => x > 2).toArray(); // [3, 4, 5]

Use .take(n) as a safety valve on potentially infinite or very large generators. Any generator that can yield unbounded values should have a .take(n) in any chain that ends with .toArray() or .reduce(). Without it, a bug in your filter condition could cause the consumer to hang:

js
// Dangerous: if no value satisfies the filter, this never terminates
Iterator.from(infiniteSource()).filter(isRare).toArray();

// Safe: guaranteed to stop
Iterator.from(infiniteSource()).filter(isRare).take(100).toArray();

Iterators are single-use. Once an iterator is consumed (fully or partially), it is exhausted. You cannot rewind or iterate it again. If you need to iterate the same data multiple times, call the factory function again to get a fresh iterator:

js
const iter = Iterator.from(mySet);
iter.take(3).toArray(); // [a, b, c]
iter.take(3).toArray(); // [] — iterator is exhausted

// Correct: create a new iterator each time
const fresh = () => Iterator.from(mySet);
fresh().take(3).toArray(); // [a, b, c]
fresh().take(3).toArray(); // [a, b, c]

Prefer .find() or .some() over .filter().toArray()[0] when you only need to check or retrieve a single element. They short-circuit on the first match and do not consume the rest of the iterator.

Engineers SHOULD NOT convert an existing .filter().map() chain on a small, already in-memory array to iterator helpers purely for performance. For small finite arrays, the eager Array methods are usually faster and simpler. The win from iterator helpers is avoiding wasted work on large, infinite, or early-exited sources, not raw throughput; see Design Thinking for the trade-off.

Design Thinking ​

Lazy evaluation is standard everywhere except JS arrays ​

Most modern languages treat iteration as inherently lazy by default. Python's built-in map() and filter() return lazy generators. No work is done until you iterate the result. Haskell's lists are lazy by construction: an infinite list [1..] is perfectly valid because nothing is evaluated until consumed. Rust's iterator adapters (.map(), .filter(), .take_while()) are famously zero-cost: the compiler fuses the entire chain into a single tight loop.

JavaScript took the opposite approach. Array methods, introduced in ES5, were designed for small, in-memory collections in an era when "big data in the browser" was not a real concern. The methods are eager: every element is transformed before returning. The Symbol.iterator protocol was added in ES6, but it was only the low-level protocol. No high-level helpers came with it.

So arrays got a method library and every other iterable got only the raw next() protocol. Iterator helpers collapse this gap.

When Array methods still win ​

Laziness is not free. Each iterator helper allocates a small helper object and drives the chain through the next() protocol one value at a time, so for a short, finite array that is already sitting in memory, Iterator.from(arr).filter(fn).map(fn).toArray() typically does more work than arr.filter(fn).map(fn). Community benchmarks comparing the two show iterator helpers pulling ahead once the source is large, the transformation chain is deep, or the consumer exits early with .take() or .find(). For small in-memory arrays, plain Array methods stay faster and simpler. Reach for iterator helpers to avoid wasted work on data you do not need in full, not as a drop-in performance upgrade for existing .filter().map() chains on small arrays.

Lodash's _.chain() was the userland answer ​

_.chain() in Lodash has been a widely used workaround for over a decade:

js
import _ from 'lodash';

const result = _.chain([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
  .filter(n => n % 2 === 0)
  .map(n => n * n)
  .take(3)
  .value(); // [4, 16, 36]

_.chain() wraps the array in a lazy wrapper that defers execution until .value() is called, though Lodash's lazy evaluation and shortcut fusion only kick in for chains long enough to qualify. The parity with iterator helpers is closest for long chains and weakest for small arrays. The bigger structural difference is that _.chain() still operates on arrays, not on the iterator protocol itself: it cannot consume generators or non-array iterables natively. Iterator helpers are the native, protocol-level version of this pattern.

Infinite sequences are now practical ​

Before iterator helpers, an infinite sequence was mostly a conceptual tool. It was useful for explaining generators but awkward to use in real code. Now, a developer can express "give me the first N even squares from the natural numbers" as a direct pipeline:

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

// First 5 even squares — reads like a specification
Iterator.from(naturals())
  .map(n => n * n)
  .filter(n => n % 2 === 0)
  .take(5)
  .toArray(); // [0, 4, 16, 36, 64]

The generator never produces the infinite list. Each step pulls one value at a time: .take(5) requests 5, .filter() pulls from .map() until 5 pass, .map() pulls from naturals() one value at a time.

Why arrays stayed eager ​

Changing Array.prototype.map() to return a lazy iterator would break the web. Thousands of codebases rely on Array.prototype.map() returning a real array immediately. The TC39 committee explicitly chose to add helpers on Iterator.prototype rather than change Array.prototype, leaving array behavior untouched. This is the same backward-compatibility discipline that gave us const/let instead of changing var.

Deep Dive ​

Complete API reference ​

Lazy methods (return a new iterator helper, no work done yet) ​

MethodDescription
.map(mapperFn)Transform each value; yields mapped values one at a time
.filter(predicateFn)Skip values that fail the predicate
.take(limit)Stop after yielding limit values
.drop(limit)Skip the first limit values, yield the rest
.flatMap(mapperFn)Map each value to an iterable, then flatten one level

Note on indexing: .map(), .filter(), .flatMap(), .forEach(), .some(), .every(), and .find() all receive (element, index), the same second argument that Array.prototype methods receive. To pair a value with its index, use iterator.map((v, i) => [i, v]). The proposal originally included a standalone method (named asIndexedPairs, later indexed) that would pair each value with its index; it was dropped before ECMAScript 2025 because the index parameter on .map() and the other methods already covers that use case.

js
const indexed = iterator.map((v, i) => [i, v]);

Eager methods (consume the iterator, trigger evaluation) ​

MethodDescription
.toArray()Collect all remaining values into an Array
.reduce(reducerFn, initialValue)Fold values into a single result
.forEach(fn)Call fn for each value; returns undefined
.some(predicateFn)Returns true if any value passes; short-circuits
.every(predicateFn)Returns true if all values pass; short-circuits on first failure
.find(predicateFn)Returns the first value that passes; short-circuits

Static method ​

MethodDescription
Iterator.from(iterableOrIterator)Wrap any iterable or iterator to gain access to Iterator.prototype helpers

How Iterator.from() works ​

Iterator.from() checks if its argument already inherits from Iterator.prototype. If it does, it returns it directly. If not, it creates a thin wrapper that delegates to the underlying iterator's next() and return() methods. This means the wrapping overhead is minimal, and any cleanup semantics of the original iterator (e.g., generator finally blocks) are preserved.

js
function* gen() {
  try {
    yield 1;
    yield 2;
    yield 3;
  } finally {
    console.log('cleaned up');
  }
}

// .take(1) calls iterator.return() to signal early termination
// The generator's finally block still runs
Iterator.from(gen()).take(1).toArray();
// logs: "cleaned up"
// returns: [1]

Subclassing Iterator ​

The Iterator class is designed to be subclassed. If you build a custom data structure with a custom iterator, you can have it inherit from Iterator and get all the helpers for free:

js
class Range extends Iterator {
  #start; #end;
  constructor(start, end) {
    super();
    this.#start = start;
    this.#end = end;
  }
  next() {
    if (this.#start >= this.#end) return { done: true, value: undefined };
    return { done: false, value: this.#start++ };
  }
}

const range = new Range(1, 11);
range.filter(n => n % 2 === 0).toArray(); // [2, 4, 6, 8, 10]

Browser Support & Version Reference ​

Availability today ​

For environments that do not yet support iterator helpers, a spec-compliant polyfill is available:

npm install iterator-helpers-polyfill

Or use the core-js polyfill with useBuiltIns: 'usage' in Babel. The polyfill patches Iterator.prototype and adds Iterator.from(). Per MDN's compatibility data, native support for every helper method (.map(), .filter(), .take(), .drop(), .flatMap(), .forEach(), .some(), .every(), .find(), .reduce(), .toArray(), and Iterator.from()) landed in Chrome 122, Firefox 131, and Safari 18.4, matching the status block above.

Sync vs. async iterator helpers ​

Everything in this article is the synchronous Iterator proposal, the one that shipped in ES2025. A separate proposal, AsyncIterator helpers, would add the same .filter()/.map()/.take() family to async iterators and async function* generators. As of mid-2026 it sits at TC39 Stage 2 and has not shipped in any browser. Until it ships, an async source needs the manual for await loop shown in Context.

TC39 Stage history ​

Iterator helpers reached Stage 4 before ECMAScript 2025 (published June 2025) and shipped as part of that release. The proposal was authored by Gus Caplan, Michael Ficarra, Adam Vandolder, Jason Orendorff, and Kevin Gibbons, and championed through TC39 by Michael Ficarra and Yulia Startsev. It sat at Stage 3 for several years while browser implementations caught up, reaching Stage 4 at the October 2024 plenary.

References ​