Get to know MDN better
Since March 2025, this feature works across the latest devices and browser versions. This feature might not work in older devices or browsers.
The flatMap() method of Iterator instances returns a new iterator helper object that takes each element in the original iterator, runs it through a mapping function, and yields elements returned by the mapping function (which are contained in another iterator or iterable).
A function to execute for each element produced by the iterator. It should return an iterator or iterable that yields elements to be yielded by flatMap(). Note that unlike Array.prototype.flatMap(), you cannot return single non-iterator/iterable values. The function is called with the following arguments:
elementThe current element being processed in the array.
indexThe index of the current element being processed in the array.
A new iterator helper object. The first time the iterator helper's next() method is called, it calls callbackFn on the first element produced by the underlying iterator, and the return value, which should be an iterator or iterable, is yielded one-by-one by the iterator helper (like yield*). The next element is fetched from the underlying iterator when the previous one returned by callbackFn is completed. When the underlying iterator is completed, the iterator helper is also completed (the next() method produces { value: undefined, done: true }).
Thrown if callbackFn returns a non-iterator/iterable value or a string primitive.
flatMap accepts two kinds of return values from callbackFn: an iterator or iterable. They are handled in the same way as Iterator.from(): if the return value is iterable, the [Symbol.iterator]() method is called and the return value is used; otherwise, the return value is treated as an iterator and its next() method is called.
The following example merges two Map objects into one:
This avoids creating any temporary copies of the map's content. Note that the array [map1, map2] must first be converted to an iterator (using Array.prototype.values()), because Array.prototype.flatMap() only flattens arrays, not iterables.
Strings are iterable, but flatMap() specifically rejects string primitives returned from callbackFn, this is because the behavior of iterating by code points is often not what you want.
You may want to wrap it in an array instead so the entire string is yielded as one:
Or, if the behavior of iterating by code points is intended, you can use Iterator.from() to convert it to a proper iterator:
| ECMAScript® 2027 Language Specification # sec-iterator.prototype.flatmap |
Enable JavaScript to view this browser compatibility table.
This page was last modified on Jul 10, 2025 by MDN contributors.
Your blueprint for a better internet.
Visit Mozilla Corporation’s not-for-profit parent, the Mozilla Foundation.
Portions of this content are ©1998–2026 by individual mozilla.org contributors. Content available under a Creative Commons license.