The first time I saw the Array method flatMap
, I naturally thought it first flats, then maps. But turned out its the other way around. If I had this function in my codebase I’d name it mapAndFlat
.
To put my argument another way, read this code out loud in English: [1, [2, 3], 4].flat(1).map(e => e * 2)
. Probably you said "flat map"
at some point, but flatMap
does not do this.
Now read this code out loud in English: [1, [2, 3], 4].map(e => e * 2).flat(1)
. Most Probably you didn’t say "flat map"
at any point, but that’s exactly what flatMap
is doing.
And I find it confusing!
To put my argument even another way, flat
and map
are both verbs (in JavaScript terminology), and when I call the Array method map
, I expect it to map (verb) the array items, which it does, and when I call the Array method flat
, I expect it to flat (verb) my array, which it does. In the same way, when an Array method is called flatMap
I expect it to do those verbs/methods in the same order I read/write, not the other way around.
Putting this nested array being map
ped and flatMap
ped as an appendix/reference for the question
> [1, [2, 3], 4].map(e => e)
[ 1, [ 2, 3 ], 4 ]
> [1, [2, 3], 4].map(e => e * 2)
[ 2, NaN, 8 ]
> [1, [2, 3], 4].flatMap(e => e)
[ 1, 2, 3, 4 ]
> [1, [2, 3], 4].flatMap(e => e * 2)
[ 2, NaN, 8 ]
I also put links to two StackOverflow questions I found, where people also mistook the flatMap
functionality (most probably) because of its name:
- Is the behavior of flatMap correct?. Where can I report a bug in Javascript?
- (Swift, not JavaScript): Swift flatMap gives unexpected result while using with optional array
When discussing this with my friends I heard two arguments:
Argument 1
flat
in flatMap
is used as an adjective for the map
, not as a verb
on its own. In my opinion, if that is the reasoning behind this, I still find it misleading. Because in EcmaScript/JavaScript terminology, we are used to flat
as a verb (on array methods). It would be misleading to change it to an adjective all of a sudden for a (relatively new) array method.
Argument 2
flatmap
is actually an old existing method in another languages (including Java, Scala, Ruby, Swift). Maybe EcmaScript just used this name so it matches other programming languages. And if that’s the case, I personally find it a bad reason to sacrifice readability.