When to Use flatMap() vs map().flat()
You'll learn when to choose flatMap() over chaining map().flat(), and vice versa, based on performance and readability.
The Core Difference
Both flatMap() and map().flat() accomplish the same goal: transforming array elements and flattening the result by one level. However, they differ in how they achieve this and when each approach makes sense.
Performance Considerations
flatMap() is slightly more efficient because it combines mapping and flattening into a single pass through the array. The map().flat() chain creates an intermediate array after map(), then flattens it—requiring two passes.
// Two passes: map creates intermediate array, then flat processes it
const doubled = [1, 2, 3].map(x => [x, x * 2]).flat();
// One pass: flatMap does both operations together
const doubled2 = [1, 2, 3].flatMap(x => [x, x * 2]);
For small arrays, the performance difference is negligible. For large datasets, flatMap() wins.
Readability Considerations
Use map().flat() when you need depth control. The flat() method accepts a depth argument, but flatMap() always flattens exactly one level:
// Need to flatten 2 levels? Can't use flatMap alone
const deep = [[1], [2], [3]].map(x => x).flat(2);
Use flatMap() when the intent is clearly "map and flatten once"—it's more concise and signals your intention directly.
Analogy
Think of map().flat() as a two-step assembly line: first shape the parts, then flatten the packaging. flatMap() is a single machine that does both operations simultaneously—faster, but less flexible.
Key Takeaway: Use flatMap() for better performance and conciseness when flattening one level; use map().flat(depth) when you need explicit depth control or want to emphasize separate transformation and flattening steps.