Misusing `map`

Unfortunately, in the past 18 months or so I'm increasingly seeing people misusing map in code like this on Stack Overflow:

    // something with `element`...

Note that:

  • The map callback doesn't return anything
  • The return value of map isn't used

This is an antipattern. Sadly, it seems like someone, somewhere, is doing their students/followers the disservice of teaching it. I don't think all of these people spontaneously started doing this on their own the last year and a half. Or maybe it's JSX, people see something like this React code:

return <ul>{ => <li>{item}</li>)}</ul>;

...and somehow don't grok that map is producing an array that's being used. So they take map as a general-purpose way of iterating arrays. (I'd prefer that explanation, but sadly I think the other is more likely.)

What makes this an antipattern?

  1. Semantics:¹ map is for a mapping operation, each A in the array becomes a B in the result array, transformed by the callback. If you're not doing mapping operation, using map is like saying "purple" when you meant to say "fruit."
  2. map creates and returns a new array (whether you use it or not). So if you get in the habit of using map instead of for-of or forEach or similar, you're getting in the habit of creating lots of unnecessary, short-lived array objects. This increases the amount of memory churn in your program, for no benefit whatsoever. It's a rare program where it will matter, but still, it's silly to add memory churn for no reason.

But semantics (loosely, the meaning of words/sentences) is the main thing. If I'm doing code maintenance and I see a map where nothing is using the result array, I see a bug — and I'll waste time looking for what was supposed to be done with that result array.

What should we do instead?

Use for-of:

for (const element of someArray) {
    // something with `element`...

...or forEach

someArray.forEach(element => {
    // something with `element`...

...or any of your other options for looping through an array.

Happy coding!

Have a question about or comment on this post? Tweet me!