DEV Community

Discussion on: Stop abusing .map()!

Collapse
 
joelbonetr profile image
JoelBonetR 🥇 • Edited

If it were so bad why they implemented it in the language API in the first hand?

There are many details in tech and you need to know why they exists. A method that copies an array with the desired data is not necessarily bad unless you use it as an average iterator instead, its what we call a reducer and it could be fine for tones of use cases.
Cloning an array is not bad itself, the bad thing is to not delete them when you don't need them anymore.

Let's add an example:

If you get a response from a REST call, for example you can get something like:

users = [{
  id: 1,
  name: 'John',
  surname: 'Doe',
  birthdate: '10-11-1980',
  email: 'john.doe@gmail.com',
  ...
}, {
  ...
}]
Enter fullscreen mode Exit fullscreen mode

If you only need to propagate the ID, the first Name character and the surname to build something like:

<span id="user.id"> user.name.charAt(0).toLowerCase() + user.surname.charAt(0).toUpperCase() + user.surname.slice(1).toLowerCase() </span>
Enter fullscreen mode Exit fullscreen mode

so you get

<span id="1"> J. Doe </span>
Enter fullscreen mode Exit fullscreen mode

Why you want to propagate the entire object in the first hand?
simply create a new array with the desired props using map and use it! you can free the old one after making your working copy and that's all.

Even that, you can make those calcs inside your map instead like I did in the code above so you get the values cooked and ready to serve in the working copy of your array and with a single line! (or 3 if you use a lint :D )


As BONUS info, you "can't" set new values on a const as is (there are ways, ok, but let's work on standard with no hacks) so if you got a const with some data and you only need a part of it, you can create your cooked copy with map and use it whenever needed, the garbage collector should do the rest.