Today I Learned - Rocky Kev

TIL map() only when you need it

POSTED ON:

TAGS:

Seeing a lot of .map() in the wild being used to solve everything.
It's mostly something I see a lot in React projects.

I love map().

What is map()?

The map() method creates a new array populated with the results of calling a provided function on every element in the calling array.

Key word: NEW ARRAY.

The origins of map() was to create methods that allow us to manipulate array data without mutating it. It's part of the whole set of methods to make functional programming easier in Javascript.

The issues with map()

Overall -- Mapping doesn't create side effects.

It creates a brand new array and shoves that data in.

So if you need to mutate that array, then do so with forEach().

If you need to make a brand new array, then go ahead and map.

// good way
const fruitIds = ['apple', 'orange', 'banana'];
fruitIds.forEach((id) => {
document.getElementById(`fruit-${id}`).classList.add('active');
});

// wrong way
const fruitIds = ['apple', 'orange', 'banana'];
fruitIds.map((id) => {
document.getElementById(`fruit-${id}`).classList.add('active');
});

// returns [undefined, undefined, undefined]

Why is it the wrong way?
Because map RETURNS a value.

But even if you passed it to another variable, say fruitIdsAttached, you've also created two versions, with one that is correct. You might as well mutate it.

The real danger is when it's a massive array, and leaving all of that data sitting there.

Fortunately, someone did some bench marking. Check it out: https://jsbench.me/ujkub8rcv2/1

ForEach is the fastest.
For...of is about 3% slower.
map is almost 50% slower.

Stop abusing .map()!

MDN - map()


Related TILs

Tagged:

TIL what is npm Script

Despite their high usage they are not particularly well optimized and add about 400ms of overhead. In this article we were able to bring that down to ~22ms.

TIL fancy methods to transform Javascript Objects

You can use Object.entries(), Object.keys(), Object.fromEntries()...

TIL how to hide your JS code

ONE THING TO NOTE: Encrypting a script is stronger than obfuscation, both methods are still not adequate to protect secret content. Honestly, I don't think it's worth it on a production site, and instead just go with pure server-side if you want security. But it's fascinating.