---
title: "Iterator helpers: map, filter and take on any iterator"
description: "JavaScript iterators now have map, filter, take and more built in. Learn how lazy iterator helpers work, where they beat arrays, and which browsers and Node versions support them."
url: https://www.danny.engineering/article/iterator-helpers-map-filter-and-take-on-any-iterator
author: Danny
published: 2026-11-27T00:00:00.000Z
updated: 2026-11-27T17:23:00.000Z
tags: ["Javascript"]
---

# Iterator helpers: map, filter and take on any iterator

Arrays have had `map`, `filter` and `reduce` for as long as most of us have been writing JavaScript. But a lot of JavaScript values are not arrays. `Map.prototype.entries()`, `Set.prototype.values()`, `String.prototype.matchAll()` and every generator function return iterators, and until recently iterators had none of those methods. The usual workaround was to spread everything into an array first, which allocates a copy and throws away any chance of stopping early.


Iterator helpers fix that. They add familiar methods directly to iterators, and they work lazily, one value at a time. This article is for JavaScript developers who are comfortable with array methods and want to know when the iterator versions are the better tool. We will cover what an iterator is, the methods you get, how laziness changes things, and where support stands.


## A quick refresher on iterators


An iterator is an object with a `next()` method that returns objects shaped like `{ value, done }`. You rarely call `next()` yourself. `for...of`, spread syntax and `Array.from` all do it for you.


```javascript
const roles = new Map([
  ["ada", "admin"],
  ["grace", "editor"],
  ["linus", "viewer"],
]);

const entries = roles.entries();
entries.next(); // { value: ["ada", "admin"], done: false }
```


Built-in iterators inherit from `Iterator.prototype`. That shared prototype is where the new helper methods live, so every built-in iterator and every generator gets them automatically.


## The methods


There are two groups. The first returns a new iterator, so you can keep chaining:

- `map(fn)`: transforms each value.
- `filter(fn)`: keeps values where `fn` returns a truthy value.
- `take(n)`: yields at most `n` values, then stops.
- `drop(n)`: skips the first `n` values.
- `flatMap(fn)`: maps each value to an iterator or iterable and flattens one level.

The second group consumes the iterator and returns a result:

- `toArray()`: collects the values into an array.
- `reduce(fn, initial)`: folds the values into one.
- `forEach(fn)`: runs `fn` for each value.
- `some(fn)`, `every(fn)` and `find(fn)`: stop as soon as the answer is known.

There is also a static `Iterator.from()`, covered below.


Callbacks receive the value and a counter, the zero-based position of the value in the sequence, much like the index argument in array methods.


```javascript
const editors = roles
  .entries()
  .filter(([, role]) => role !== "viewer")
  .map(([name]) => name)
  .toArray();

// ["ada", "grace"]
```


Compare that with the older version, which builds an intermediate array:


```javascript
const editors = [...roles.entries()]
  .filter(([, role]) => role !== "viewer")
  .map(([name]) => name);
```


For three entries the difference is invisible. For a large map, or a source that produces values slowly, it starts to matter.


## Laziness


Array methods are eager. Each step runs over the whole array and builds a new one before the next step starts. Iterator helpers are lazy. Nothing happens until something asks for a value, and then each value travels through the whole chain before the next one is pulled.


```javascript
function* naturals() {
  let n = 1;
  while (true) {
    console.log("producing", n);
    yield n++;
  }
}

const firstSquares = naturals()
  .filter((n) => n % 2 === 0)
  .map((n) => n * n)
  .take(3)
  .toArray();

console.log(firstSquares); // [4, 16, 36]
// "producing" is logged six times, not forever
```


`naturals()` never ends, yet this finishes, because `take(3)` stops pulling after three values reach it. With arrays you cannot even start, since you would need to build an infinite array first.


Laziness also means a chain on its own does nothing. This line runs no callbacks at all:


```javascript
const pending = naturals().map((n) => n * 2);
```


Work happens only when you consume `pending` with `toArray()`, `for...of`, spread or one of the other consuming methods.


## Real-world uses


### Filtering a Map without converting it


The `Map` constructor accepts any iterable of entries, and helper iterators are iterable, so you can filter a map into a new map in one expression.


```javascript
const stock = new Map([
  ["apples", 12],
  ["pears", 0],
  ["plums", 4],
]);

const inStock = new Map(stock.entries().filter(([, count]) => count > 0));
// Map { "apples" => 12, "plums" => 4 }
```


### Working with regular expression matches


`matchAll` returns an iterator of match objects, which pairs nicely with `map`.


```javascript
const text = "Release notes for #typescript and #javascript";

const tags = text
  .matchAll(/#(\w+)/g)
  .map((match) => match[1])
  .toArray();

// ["typescript", "javascript"]
```


### Taking the first few results from an expensive source


Generators are a natural way to describe paged data. Iterator helpers let callers decide how much they need.


```javascript
function* chunks(items, size) {
  for (let i = 0; i < items.length; i += size) {
    yield items.slice(i, i + size);
  }
}

const firstTwoBatches = chunks(bigList, 100).take(2).toArray();
```


Only the first two slices are ever made, however long `bigList` is.


### DOM collections


`NodeList` has a `values()` method that returns an iterator, so you can chain helpers onto the result of `querySelectorAll`.


```javascript
const missingAlt = document
  .querySelectorAll("img")
  .values()
  .filter((img) => !img.alt)
  .toArray();
```


### Iterator.from


Some objects implement the iterator protocol by hand without inheriting from `Iterator.prototype`, so they do not have the helpers. `Iterator.from()` wraps them. It also accepts any iterable, such as an array or a string.


```javascript
const countdown = {
  n: 3,
  next() {
    return this.n > 0 ? { value: this.n--, done: false } : { value: undefined, done: true };
  },
};

Iterator.from(countdown).map((n) => `${n}...`).toArray();
// ["3...", "2...", "1..."]
```


## Things to watch for

- **Iterators are single use.** Once you consume one, it is finished. Calling `toArray()` twice on the same chain gives you the values the first time and an empty array the second. If you need several passes, collect into an array once.
- **There is no length, index access, sort or reverse.** Those need all the values at once. Use `toArray()` and then array methods.
- **take and drop validate their argument.** Passing a negative number or `NaN` throws a `RangeError`.
- **Stopping early closes the source.** When `take` has enough values, or `find` gets a match, the helper calls `return()` on the underlying iterator, so a generator's `finally` block runs and resources can be released.
- **Async iterators are not covered.** These helpers only work on synchronous iterators. Async iterator helpers are a separate proposal and are not widely available yet. For async sources, use `for await...of` or `Array.fromAsync`.

## Browser support


Iterator helpers are Baseline newly available since 31 March 2025, when Safari shipped them. The first supporting versions are:

- Chrome and Edge 122
- Firefox 131
- Safari 18.4, on macOS and iOS

On the server they are available in Node 22 and later, so every supported Node release has them. They are expected to reach Baseline widely available in late 2027. If you need to support older Safari versions before then, core-js provides a polyfill.


For TypeScript users, the type definitions for iterator helpers come with a recent `lib` or `target` setting, such as `esnext`. If the methods show as missing in your editor, check that your `lib` includes a recent ECMAScript version.


## When not to use it

- **You already have an array.** Array methods are well known, give you an index, and do not need a conversion step. Turning an array into an iterator just to call `map` adds nothing.
- **You need the data more than once.** An iterator is gone after one pass. Build an array if you will sort, reverse, count or loop again.
- **You need random access or the total count.** Those need every value up front.
- **Your audience includes older Safari without a polyfill.** Until widely available status, check your analytics before relying on them in browser code.

## Wrapping up

- Every built-in iterator and generator now has `map`, `filter`, `take`, `drop`, `flatMap`, `reduce`, `toArray`, `forEach`, `some`, `every` and `find`.
- They are lazy: values flow through the chain one at a time, so you can stop early and even work with infinite sequences.
- They save you from spreading `Map`, `Set`, `matchAll` and `NodeList` results into arrays just to transform them.
- Iterators are single use. Collect with `toArray()` when you need multiple passes or array-only operations.
- Supported in Chrome and Edge 122, Firefox 131, Safari 18.4 and Node 22 and later.
