JavaScript Iterator Helpers: map, filter, take, drop, flatMap and reduce on Any Iterator (ES2025)
ES2025 iterator helpers bring map, filter, take, drop, flatMap, reduce, toArray, forEach, some, every and find to every iterator, lazily. Learn how they differ from array methods, Iterator.from, working with Maps, Sets and generators, infinite pipelines, cleanup, Iterator.concat and Array.fromAsync.
kvi5hnuCode Sprout team member7 min readOn this page
Before ES2025, iterators had exactly one method: next(). To filter the keys of a Map or take the first ten values of a generator, you had to spread everything into an array first ([...map.keys()].filter(...)) or write helper generators like take by hand (article 91). Iterator helpers, standardized in ES2025 and supported in all current browsers and Node.js 22+, add familiar methods directly to iterators, and they're lazy.
The helper methods
All built-in iterators (from arrays, strings, Maps, Sets, generators, matchAll and so on) inherit from Iterator.prototype, which now has:
| Method | Returns | Does |
|---|---|---|
map(fn) | iterator | transforms each value |
filter(fn) | iterator | keeps values where fn is truthy |
take(n) | iterator | the first n values, then stops |
drop(n) | iterator | skips the first n values |
flatMap(fn) | iterator | maps each value to an iterable and flattens one level |
reduce(fn, initial?) | value | combines all values |
toArray() | array | collects the values |
forEach(fn) | undefined | runs fn for each value |
some(fn) / every(fn) | boolean | stops as soon as the answer is known |
find(fn) | value or undefined | first matching value |
The first five return new iterators (they're lazy); the rest consume the iterator and return a result. Callbacks receive (value, index), where the index counts values seen so far.
function* naturals() {
let n = 1;
while (true) yield n++;
}
console.log(naturals().filter((n) => n % 3 === 0).map((n) => n * n).take(4).toArray());
console.log(naturals().drop(5).take(3).toArray(), naturals().take(5).reduce((sum, n) => sum + n, 0));
console.log(naturals().some((n) => n > 1000), naturals().find((n) => n ** 2 > 50));
[ 9, 36, 81, 144 ]
[ 6, 7, 8 ] 15
true 8
naturals() never ends, yet every line finishes, because each helper pulls only as many values as it needs. The same code with arrays is impossible: you can't build an infinite array.
Lazy vs eager

Array methods are eager: .map() processes the whole array and returns a new array before .filter() starts. Iterator helpers are lazy: building the pipeline does nothing, and each value travels through all the stages before the next value is produced.
function* source() {
for (const n of [1, 2, 3, 4]) {
console.log(" produce", n);
yield n;
}
}
const pipeline = source()
.map((n) => { console.log(" map", n); return n * 10; })
.filter((n) => n > 15);
console.log("pipeline built");
console.log("first result:", pipeline.next().value);
pipeline built
produce 1
map 1
produce 2
map 2
first result: 20
Nothing ran until next() was called, and only two values were produced to get the first result. Laziness means:
- No intermediate arrays, which saves memory for big data.
- Early exit:
take,find,someandeverystop pulling as soon as they can. - Infinite sources are fine, as long as something limits them.
Using helpers with arrays, Maps, Sets and strings
Arrays already have eager map and filter that return arrays. Call values() to get an iterator when you want the lazy versions, for example to stop early on a large array:
const words = "the quick brown fox jumps over the lazy dog".split(" ");
console.log(words.values().filter((w) => w.length > 4).take(2).toArray());
const ages = new Map([["ana", 31], ["bo", 25], ["cy", 40]]);
console.log(ages.entries().filter(([, age]) => age > 30).map(([name]) => name).toArray());
console.log(Object.fromEntries(ages.entries().map(([name, age]) => [name.toUpperCase(), age])));
console.log(new Set([1, 2, 3]).values().map((x) => x * 2).toArray());
console.log("hey"[Symbol.iterator]().map((c) => c.toUpperCase()).toArray().join(""));
[ 'quick', 'brown' ]
[ 'ana', 'cy' ]
{ ANA: 31, BO: 25, CY: 40 }
[ 2, 4, 6 ]
HEY
This is the biggest everyday win: transforming Maps and Sets no longer needs [...map] or Array.from in the middle.
Remember that helpers return iterators, not arrays. Finish with toArray() (or spread, Array.from, new Set, Object.fromEntries, a for...of loop) when you need a collection.
flatMap
flatMap(fn) expects fn to return an iterator or iterable and yields its values:
const lines = ["red green", "blue"];
console.log(lines.values().flatMap((line) => line.split(" ")).toArray());
try {
["a"].values().flatMap((s) => s.toUpperCase()).toArray();
} catch (err) {
console.log(err.name);
}
[ 'red', 'green', 'blue' ]
TypeError
Unlike Array.prototype.flatMap, it doesn't accept non-iterable return values, and it deliberately rejects strings (to avoid accidentally splitting a string into characters). Return [value] to yield a single value.
Iterator.from: helpers for any iterator
Iterators you write by hand, or get from libraries, may not inherit from Iterator.prototype. Iterator.from(obj) wraps any iterator or iterable so it gets the helpers:
const countdown = {
n: 3,
next() {
return this.n > 0 ? { value: this.n--, done: false } : { value: undefined, done: true };
},
};
const wrapped = Iterator.from(countdown);
console.log(wrapped instanceof Iterator, wrapped.map((x) => x * 100).toArray());
true [ 300, 200, 100 ]
You can also make your own iterator classes extend the global Iterator class (class Ticks extends Iterator { next() { /* ... */ } }): they inherit every helper, and [Symbol.iterator]() { return this; } too, so they work with for...of and spread.
Cleanup and one-shot behavior
When a helper stops early, it calls return() on the source iterator, so generators' finally blocks run (article 92):
function* readRows() {
try {
yield "row 1";
yield "row 2";
yield "row 3";
} finally {
console.log(" source closed");
}
}
console.log(readRows().take(1).toArray());
source closed
[ 'row 1' ]
And like all iterators, helper iterators are one-shot:
const doubled = [1, 2, 3].values().map((x) => x * 2);
console.log(doubled.toArray(), doubled.toArray());
[ 2, 4, 6 ] []
If you need the results twice, store the array from toArray(), or rebuild the pipeline from the original iterable.
Edge cases and errors
takeanddropneed a non-negative number;take(-1)throws aRangeError.reducewith no initial value on an empty iterator throws aTypeError, exactly like arrays.forEachreturnsundefinedand can't be stopped early; usesome,findor afor...ofloop withbreakinstead.- Callbacks get
(value, index), not the array-style third argument.
Newer additions: Iterator.concat and Array.fromAsync
Iterator.concat(...iterables)(iterator sequencing) reached Stage 4 in late 2025 and is part of ES2026. It chains iterables into one lazy iterator, like theconcatgenerator in article 91. Engines are rolling it out (Node 25 doesn't have it yet);function* concat(...its) { for (const it of its) yield* it; }is the fallback.Array.fromAsync(asyncIterable)(ES2026, shipped by engines since 2024) collects an async iterable or an iterable of promises into an array, the async counterpart ofArray.from. It's covered with async iteration in Part 13.- Async iterator helpers (
map,filterand friends on async iterators) are still a proposal.
Coming in ES2027: zip, chunks, windows, includes and join
Several more helpers reached Stage 4 for ES2027. Engines are still shipping them, so check support before relying on them:
Iterator.zip(iterables, options)walks several iterables in step and yields arrays:Iterator.zip([names, scores])gives["Ada", 91],["Lin", 78], and so on. By default it stops at the shortest input (mode: "shortest").mode: "longest"continues withundefinedor apaddingvalue, andmode: "strict"throws if the lengths differ.Iterator.zipKeyed({ a: ..., b: ... })yields objects keyed like its argument instead.iterator.chunks(n)yields arrays ofnitems, with a shorter final chunk.iterator.windows(n)yields overlapping windows:[1, 2],[2, 3],[3, 4]...iterator.includes(value)anditerator.join(separator)work like the array methods of the same names, consuming the iterator as they go.
Generators implement the same lazy behavior today:
// ES2027 adds iterator.chunks(n) and Iterator.zip(...). Until your engine has them,
// generators give the same lazy behavior.
function* chunks(iterable, size) {
let chunk = [];
for (const item of iterable) {
chunk.push(item);
if (chunk.length === size) { yield chunk; chunk = []; }
}
if (chunk.length > 0) yield chunk; // the last chunk may be shorter
}
function* zip(iterables) { // like Iterator.zip's default "shortest" mode
const iterators = iterables.map((it) => it[Symbol.iterator]());
while (true) {
const results = iterators.map((it) => it.next());
if (results.some((r) => r.done)) return;
yield results.map((r) => r.value);
}
}
console.log([...chunks("abcdefg", 3)]);
const names = ["Ada", "Lin", "Grace"];
const scores = new Set([91, 78, 85]);
for (const [name, score] of zip([names, scores, [1, 2]])) console.log(name, score);
[ [ 'a', 'b', 'c' ], [ 'd', 'e', 'f' ], [ 'g' ] ]
Ada 91
Lin 78
Common questions
Should I replace array methods with iterator helpers?
No. For arrays you'll fully process, array methods are simple and fast. Reach for iterator helpers with Maps, Sets, generators, large data where you'll stop early, or infinite sequences.
Why does [1, 2, 3].values().map(fn) not give an array?
Iterator map returns a lazy iterator. Call .toArray() or spread it. Arrays' own map (without .values()) returns an array.
Do helpers work in older browsers?
They're supported in current Chrome, Edge, Firefox and Safari and in Node.js 22+. For older environments, core-js provides a polyfill.
Are iterator helpers slower than array methods?
Per element they can have a bit more overhead, but they avoid intermediate arrays and stop early, which often makes whole pipelines faster and lighter on memory. Measure if it matters.
Summary
- ES2025 added
map,filter,take,drop,flatMap(lazy, returning iterators) andreduce,toArray,forEach,some,every,find(consuming) toIterator.prototype. - They're lazy: values flow one at a time through the pipeline, so early exits and infinite sources work and no temporary arrays are built.
- Use
array.values(),map.entries(),set.values()and generators as sources; finish withtoArray()or another consumer. Iterator.fromadds helpers to any iterator; extendingIteratorgives your classes the helpers too.- Helpers close the source iterator when they stop early, and they're one-shot.
Iterator.concat(ES2026) andArray.fromAsync(ES2026) round out the toolkit.
Review quiz
Check your understanding of iterables, iterators, generators, yield*, next/return/throw and iterator helpers: Part 12 review quiz: Iterators and Generators.
Practice Questions
Get the first three even squares greater than 50 from an infinite naturals() generator.
Answer
naturals().map((n) => n * n).filter((sq) => sq > 50 && sq % 2 === 0).take(3).toArray()
Gives [ 64, 100, 144 ].
How do you get the names of users older than 30 from a Map like this, without spreading it into an array?
const users = new Map([[id, { name, age }], ...])
Answer
users.values().filter((u) => u.age > 30).map((u) => u.name).toArray()
What does this code print?
const it = [1, 2, 3, 4].values();
it.take(2).toArray();
console.log(it.toArray());
Answer
[ 3, 4 ]. take(2) pulled two values and then tried to close the source with return(), but array iterators have no return method, so the array iterator simply stays where it was. (A generator source would have been finished by that return() call.)
Why does this code throw when label is a string?
iter.flatMap((x) => x.label)
Answer
Iterator flatMap requires the callback to return an iterator or a non-string iterable. Return [x.label] to emit one value, or use map if you don't need flattening.
Next: Asynchronous JavaScript: Callbacks, the Event Loop, Tasks and Microtasks

More in JavaScript Course
Quiz: Modern JavaScript, ES2022 to ES2027 Features
Twenty-four questions on what's new in JavaScript: change-array-by-copy methods, groupBy, Set methods, iterator helpers, Promise.withResolvers and Promise.try, RegExp.escape and the v flag, using declarations, Error.isError, Base64 typed arrays, Temporal, getOrInsert and Iterator.zip.
Quiz: JavaScript's Delicate Details (Spec-Level Edge Cases)
Twenty-eight questions on the fine print of JavaScript, drawn from the ECMAScript specification and MDN: sparse arrays, -0, number limits, JSON edge cases, Date overflow, UTF-16, property attributes, inherited accessors, comparison quirks, labels, regex state and Symbol.toPrimitive.
Quiz: JavaScript Interview Questions (Output Prediction and Core Concepts)
Thirty classic JavaScript interview questions: closures in loops, hoisting and the TDZ, this, the event loop and microtasks, async/await, coercion, sorting and parseInt traps, prototypes, copying, finally, generators and bind. Every answer was verified by running it.
Quiz: JavaScript Course Final Exam (All 17 Parts)
The final exam for the JavaScript course: thirty questions spanning all seventeen parts, from syntax, types and operators through objects, arrays, functions, classes, modules, the standard library, iterators, async code, metaprogramming, browsers, Node.js and tooling.
Discussion
Sign in to ask a question or share what you learned.