Iterator Helpers

Updated · 7 min read
hardES2026javascriptiteratorsiterator-helperses2025es2026

Iterator helpers are methods like map, filter and take that work directly on iterators, added in ES2025. Array methods process a whole array at once and build a new array at every step; iterator helpers process items lazily, one at a time, only as many as the consumer asks for. That makes them ideal for large data, infinite sequences and generator pipelines. ES2026 adds Iterator.concat to join iterators and Array.fromAsync to collect async iterables.

In One Minute

  • Every built-in iterator (from arrays, Maps, Sets, generators...) has helper methods: .map, .filter, .take, .drop, .flatMap.
  • Lazy helpers return new iterators; nothing runs until you consume them.
  • Consuming helpers return results: .toArray(), .reduce(), .forEach(), .some(), .every(), .find().
  • Iterator.from(obj) wraps any iterable or iterator so it gets the helpers.
  • Iterator.concat(a, b) (ES2026) joins iterables; Array.fromAsync(asyncIterable) collects async sequences.

Helper Methods

MethodLazy?Description
map(fn)YesIt is used to transform each value.
filter(fn)YesIt is used to keep values that pass the test.
take(n)YesIt is used to stop after n values.
drop(n)YesIt is used to skip the first n values.
flatMap(fn)YesIt is used to map each value to an iterable and flatten one level.
toArray()ConsumesIt is used to collect the values into an array.
reduce(fn, init)ConsumesIt is used to combine values into one.
forEach(fn)ConsumesIt is used to run fn for each value.
some(fn), every(fn), find(fn)Consumes (stops early)It is used to test or search the values.

Callbacks receive (value, index), where index counts from 0.

A First Pipeline

pipeline.js▶ Try it
const payments = [120, 30, 85, 450, 20, 60];
 
const result = payments
  .values()
  .filter((amount) => amount >= 50)
  .map((amount) => `$${amount}`)
  .take(3)
  .toArray();
 
console.log(result);
Output
['$120', '$85', '$450']

Explanation: payments.values() gives an iterator over the array. filter, map and take each return a new lazy iterator wrapping the previous one; toArray() finally pulls values through the chain. Unlike the array version (payments.filter(...).map(...).slice(0, 3)), no intermediate arrays are created, and processing stops as soon as three values have been taken.

Laziness in Action

Logging inside the callbacks shows that each value travels through the whole pipeline before the next value starts, and that work stops when take is satisfied:

lazy.js▶ Try it
const log = [];
const result = [120, 30, 85, 450, 20]
  .values()
  .filter((a) => { log.push(`filter ${a}`); return a >= 50; })
  .map((a) => { log.push(`map ${a}`); return a * 2; })
  .take(2)
  .toArray();
 
console.log(result);
console.log(log.join(", "));
Output
[240, 170]
filter 120, map 120, filter 30, filter 85, map 85

Only the first three values were looked at; 450 and 20 were never touched. With array methods, filter would have checked all five values and map would have processed every survivor before anything was cut off.

Infinite Sequences, Safely

Laziness makes infinite generators practical. take and drop bound them:

infinite.js▶ Try it
function* naturals(start = 1) {
  for (let n = start; ; n++) yield n;
}
 
const firstEvenSquares = naturals()
  .map((n) => n * n)
  .filter((n) => n % 2 === 0)
  .take(4)
  .toArray();
console.log(firstEvenSquares);
 
const receipts = naturals(1001).map((n) => `R-${n}`);
console.log(receipts.drop(2).take(3).toArray());
Output
[4, 16, 36, 64]
['R-1003', 'R-1004', 'R-1005']

Without take, calling toArray() on an infinite iterator would never finish. Always bound infinite sequences before consuming them.

Consuming Helpers

consumers.js▶ Try it
const amounts = () => [120, 85, 45, 200].values();
 
console.log(amounts().reduce((sum, a) => sum + a, 0));
console.log(amounts().some((a) => a > 150));
console.log(amounts().every((a) => a > 0));
console.log(amounts().find((a) => a < 50));
amounts().take(2).forEach((a, i) => console.log(`#${i + 1}: $${a}`));
Output
450
true
true
45
#1: $120
#2: $85

Each consumption uses up the iterator, which is why the example calls amounts() to get a fresh one each time. some, every and find stop as soon as they know the answer.

Iterator.from

Helpers live on Iterator.prototype, which built-in iterators inherit from. To use them on an iterable that isn't an iterator (or on a hand-written iterator object), wrap it with Iterator.from:

from.js▶ Try it
const grades = new Set([9, 10, 11, 12]);
console.log(Iterator.from(grades).filter((g) => g >= 11).toArray());
 
const handMade = { i: 0, next() { return this.i < 3 ? { value: this.i++, done: false } : { done: true }; } };
console.log(Iterator.from(handMade).map((n) => n * 10).toArray());
 
console.log(Iterator.from("abc").map((c) => c.toUpperCase()).toArray());
Output
[11, 12]
[0, 10, 20]
['A', 'B', 'C']

Sets, Maps and strings are iterables; grades.values() would also work for the Set. Iterator.from is the general way in.

Iterator.concat (ES2026)

Iterator.concat(...iterables) returns one lazy iterator that yields everything from the first iterable, then the second, and so on:

concat.js▶ Try it
const fall = ["Tuition", "Books"];
const spring = new Set(["Tuition", "Lab"]);
function* summer() { yield "Camp"; }
 
const allItems = Iterator.concat(fall, spring, summer());
console.log(allItems.toArray());
 
const unique = new Set(Iterator.concat(fall, spring));
console.log([...unique]);
Output
['Tuition', 'Books', 'Tuition', 'Lab', 'Camp']
['Tuition', 'Books', 'Lab']

It works with any mix of iterables, without copying them into a combined array first.

Array.fromAsync

Array.fromAsync(asyncIterable) (ES2026) is the async counterpart of Array.from: it consumes an async iterable (or an iterable of promises) and returns a promise of an array:

from-async.js▶ Try it
async function* pages() {
  for (const page of [["Navika", "Srihitha"], ["Advitha"]]) {
    await new Promise((r) => setTimeout(r, 5));
    yield* page;
  }
}
 
console.log(await Array.fromAsync(pages()));
console.log(await Array.fromAsync(pages(), (name) => name.toUpperCase()));
console.log(await Array.fromAsync([Promise.resolve(1), 2]));
Output
['Navika', 'Srihitha', 'Advitha']
['NAVIKA', 'SRIHITHA', 'ADVITHA']
[1, 2]

Arrays or Iterator Helpers?

SituationUse
Small arrays, need indexes, sorting, or several passesArray methods
Large data where you only need some resultsIterator helpers (take, find)
Infinite or generated sequencesIterator helpers
Data from generators, Maps, SetsIterator helpers (no copying to an array first)
SortingArrays (toSorted), since sorting needs every value anyway

In Practice

The Fee Tracker scans a large stream of imported rows, keeping only valid unpaid ones and stopping after the first 3 for a preview, without ever building the full intermediate lists:

preview.js▶ Try it
function* importRows(count) {
  for (let i = 1; i <= count; i++) {
    yield { id: i, name: ["Navika", "Srihitha", "Advitha"][i % 3], amount: (i * 37) % 500, paid: i % 4 === 0 };
  }
}
 
let examined = 0;
const preview = importRows(1_000_000)
  .map((row) => { examined++; return row; })
  .filter((row) => !row.paid && row.amount >= 100)
  .map((row) => `#${row.id} ${row.name}: $${row.amount}`)
  .take(3)
  .toArray();
 
console.log(preview);
console.log(`examined ${examined} of 1,000,000 rows`);
Output
['#3 Navika: $111', '#5 Advitha: $185', '#6 Navika: $222']
examined 6 of 1,000,000 rows

Common Mistakes

Calling helpers on an array directly. [1, 2].take(1) doesn't exist: arrays have array methods. Call .values() first, or use Iterator.from.

Consuming an iterator twice. It's empty the second time. Create a new one, or collect with toArray() once.

toArray() on an infinite iterator. It never finishes. Bound it with take.

Expecting helpers on async iterators. They aren't standard yet. Use for await or Array.fromAsync.

Practice

Challenge: Using iterator helpers on the infinite naturals() generator, find the first 3 numbers greater than 100 that are divisible by both 7 and 9.

Show solution
divisible.js▶ Try it
function* naturals() {
  for (let n = 1; ; n++) yield n;
}
 
console.log(naturals().filter((n) => n > 100 && n % 7 === 0 && n % 9 === 0).take(3).toArray());
Output
[126, 189, 252]

Quick check: Iterator helpers

3 questions
1What does [1, 2, 3].values().map((x) => x * 2) return?
2Why can iterator helpers handle infinite sequences?
3How do you use helpers on a Set?

Key Takeaways

TaskCode
From an arrayarr.values().filter(fn).toArray()
From any iterableIterator.from(set).map(fn)
First n.take(n)
Skip n.drop(n)
Join sequencesIterator.concat(a, b)
Collect asyncawait Array.fromAsync(asyncIterable)

Was this tutorial helpful?

Lesson 110 of 139