# Iterator.flatMap()

> The `.flatMap()` JS method of the `Iterator` object maps each value to an iterable and flattens the results.

## How do I use flatMap on an iterator in JavaScript?

The method that returns a new iterator, calling a callback for each value and yielding all values from the iterables it returns, one level deep.

- Topic: Iterator
- Type: method
- Browser support: Chrome 122+, Chrome Android 122+, Edge 122+, Firefox 131+, Firefox Android 131+, Safari 18.4+, Safari iOS 18.4+

## Example

Wrong:

```js
const chars = words.values()
  .flatMap((word) => word)
  .toArray(); // TypeError
```

Right:

```js
const chars = words.values()
  .flatMap((word) => [...word])
  .toArray();
```

Iterator `flatMap()` rejects strings returned from the callback; spreading the string into an array yields its characters.

## Common mistakes

- Returning a string from the callback, which throws a `TypeError` instead of splitting it.

## Key points

- The callback returns an iterator or an iterable object such as an array, not a string.
- Lazy `flatMap()` on the iterator is used instead of building nested arrays first.

## Interview questions

### How deep does iterator `flatMap()` flatten?

One level. Each value returned by the callback is iterated, but nested arrays inside it stay as they are.

### Is there an iterator `flat()` method?

No. Use `flatMap((x) => x)` to flatten one level of iterables.

## Related cards

- [Iterator.map()](https://wonderium.dev/js/iterator-map.md)
- [Array.flatMap()](https://wonderium.dev/js/array-flat-map.md)
- [Iterator](https://wonderium.dev/js/iterator.md)
- [Generator](https://wonderium.dev/js/generator.md)

---

- Level: [JavaScript](https://wonderium.dev/js.md)
- HTML version: https://wonderium.dev/js/iterator-flat-map
- Last updated: 2026-11-25
