Sub topic 15
Iterator Helper Methods
The previous chapter built lazy pipelines from small generator functions such as map and take. ES2025 adds methods to Iterator.prototype that do the same work, so most of those hand-written helpers are no longer needed. This chapter covers what the helper methods are, how they behave, where they differ from array methods, and the errors people commonly run into.
This chapter assumes you already know:
- the iterator protocol (
next()and{ value, done }) - how generators pause and resume
- how
return()cleans up when a loop exits early - the lazy pipelines from the previous chapter
Where the methods live
Almost every built-in iterator inherits from Iterator.prototype. That includes generator objects, the iterators returned by array.values(), map.entries(), and set.keys(), and string iterators. Because of that shared parent, the helpers are available on all of them.
Arrays, Maps, and Sets are not iterators themselves, so they don't have these methods. To use the helpers on them, first ask for an iterator:
const scores = new Map([['ana', 3], ['ben', 1], ['cy', 5]]);
const winners = scores.entries()
.filter(([, points]) => points > 2)
.map(([name]) => name)
.toArray();
console.log(winners); // [ 'ana', 'cy' ]The methods fall into two groups.
| Group | Methods | Returns | Runs when |
|---|---|---|---|
| Lazy (chainable) | `map`, `filter`, `take`, `drop`, `flatMap` | a new iterator helper object | values are pulled |
| Eager (terminal) | `toArray`, `reduce`, `forEach`, `some`, `every`, `find` | a plain value | immediately |
The static method Iterator.from belongs to neither group. It converts something else into a proper iterator, and it is covered later in this chapter.
Laziness, shown step by step
A lazy method does no work when you call it. It returns a new iterator that remembers its source and its callback. Work happens only when something calls next() on the end of the chain. Each value is pulled through all the stages before the next value starts.
function* source() {
for (let i = 1; i <= 5; i++) {
console.log('produce', i);
yield i;
}
}
const pipeline = source()
.map(n => { console.log(' map', n); return n * 10; })
.filter(n => { console.log(' filter', n); return n > 10; })
.take(2);
console.log('pipeline built, nothing produced yet');
console.log(pipeline.toArray());
// pipeline built, nothing produced yet
// produce 1
// map 1
// filter 10
// produce 2
// map 2
// filter 20
// produce 3
// map 3
// filter 30
// [ 20, 30 ]The source never produces 4 or 5. Once take(2) has its second value, it reports done: true. It also calls return() on the stage before it, and that call travels back to the generator. Cleanup therefore works the same way as breaking out of for...of: a finally block in the source generator still runs.
Because the helpers are lazy, they are safe to use on infinite sequences. This is the same pipeline you hand-wrote in the previous chapter:
function* naturals() {
let n = 0;
while (true) yield n++;
}
const firstSquaresOver50 = naturals()
.map(n => n * n)
.filter(n => n > 50)
.take(3)
.toArray();
console.log(firstSquaresOver50); // [ 64, 81, 100 ]The methods one by one
The map, filter, flatMap, reduce, forEach, some, every, and find callbacks receive (value, counter). The counter starts at 0 and counts the values that stage has seen. Callbacks do not get a third "whole collection" argument the way array callbacks do, because the full collection may not exist yet.
function* letters() { yield 'a'; yield 'b'; yield 'c'; yield 'd'; }
console.log(letters().drop(1).toArray()); // [ 'b', 'c', 'd' ]
console.log(letters().map((ch, i) => `${i}:${ch}`).toArray()); // [ '0:a', '1:b', '2:c', '3:d' ]
console.log(letters().flatMap(ch => [ch, ch.toUpperCase()]).take(4).toArray());
// [ 'a', 'A', 'b', 'B' ]
console.log(letters().reduce((acc, ch) => acc + ch, '')); // 'abcd'
console.log(letters().some(ch => ch === 'b')); // true (stops after 'b')
console.log(letters().every(ch => ch < 'c')); // false (stops at 'c')
console.log(letters().find(ch => ch > 'a')); // 'b'
letters().forEach((ch, i) => console.log(i, ch)); // 0 a, 1 b, ...The methods some, every, and find stop as soon as they know the answer, and they close the source iterator when they stop.
Iterator.from
Some objects have a next() method but don't inherit from Iterator.prototype. Hand-written iterators like the one from the "Building a Custom Iterable by Hand" chapter are an example. Iterator.from wraps such an object so the helpers become available. It also accepts any iterable, such as a string or a Set. If the iterator it receives already inherits from Iterator.prototype, it returns that iterator unchanged.
const countdown = {
n: 3,
next() {
return this.n > 0
? { value: this.n--, done: false }
: { value: undefined, done: true };
}
};
console.log(Iterator.from(countdown).map(x => x * 2).toArray()); // [ 6, 4, 2 ]
console.log(Iterator.from('hi').map(c => c.toUpperCase()).toArray()); // [ 'H', 'I' ]To make your own iterator objects work with the helpers without wrapping them, create them with Object.create(Iterator.prototype) or extend the global Iterator class (class MyIter extends Iterator { next() { ... } }).
Gotchas
| Situation | What happens |
|---|---|
| `[1, 2].map` vs `[1, 2].values().map` | The first is the eager array method and returns an array. The second is lazy and returns an iterator. |
| Reusing a chain | Helpers are one-shot like any iterator. A second `toArray()` returns `[]`. |
| `take(-1)`, `drop(NaN)` | Throws `RangeError` when you call `take` or `drop`, before any value is pulled. |
| `reduce` with no initial value on an empty iterator | Throws `TypeError`, as `Array.prototype.reduce` does. |
| `flatMap` callback returns a string | Throws `TypeError`. Strings are not flattened, so return `[...str]` if you want characters. |
| Calling the method on a plain object with only `next()` | `TypeError: ...map is not a function`. Wrap the object with `Iterator.from`. |
| No `length`, no indexing, no `sort` | The helpers are sequential only. Call `toArray()` first if you need these. |
The one-shot rule affects how you build pipelines. You can store a chain in a variable and consume it later, but only once. If you need the same pipeline more than once, wrap it in a function that builds a new chain on each call:
const evensTimesTen = () => [1, 2, 3, 4].values()
.filter(n => n % 2 === 0)
.map(n => n * 10);
console.log(evensTimesTen().toArray()); // [ 20, 40 ]
console.log(evensTimesTen().toArray()); // [ 20, 40 ]When to use them, and runtime support
Use the helpers when the data is an iterator already, such as a generator or map.entries(). They also help when the data is large or infinite, or when you want to stop early without building intermediate arrays. For small arrays that are already in memory, array methods are just as clear and can be faster.
Current engines ship the helpers: Chrome and Edge 122+, Firefox 131+, Safari 18.4+, and Node.js 22+. Older targets need a polyfill (core-js provides one) or the generator helpers from the previous chapter. You can check for support at runtime:
const hasIteratorHelpers =
typeof Iterator !== 'undefined' &&
typeof Iterator.prototype.map === 'function';
console.log(hasIteratorHelpers);Exercise
Given function* gen() { try { yield 1; yield 2; yield 3; } finally { console.log('closed'); } }, what does console.log(gen().map(x => x + 1).take(1).toArray()) print, and in what order?
Show answer
It prints closed, then [ 2 ]. The take(1) stage receives 2 and then, on the next pull, calls return() on the stage before it. That call reaches the generator and runs its finally block before toArray() returns the array.
Exercise
Why does new Set([1, 2, 3]).map(x => x * 2) throw, and how do you fix it while keeping the code lazy?
Show answer
A Set is iterable but is not an iterator, so it doesn't inherit from Iterator.prototype and has no map method. Call new Set([1, 2, 3]).values().map(x => x * 2), or use Iterator.from(new Set([1, 2, 3])).map(x => x * 2). Both return a lazy iterator.
Exercise
Using only iterator helpers and the naturals() generator, get the first five numbers that are divisible by 3 but not by 2, skipping the very first match.
Show answer
naturals().filter(n => n % 3 === 0 && n % 2 !== 0).drop(1).take(5).toArray() returns [ 9, 15, 21, 27, 33 ]. The first match, 3, is dropped.