TIL map() only when you need it
POSTED ON:
TAGS: javascript performance loops
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.
Related TILs
Tagged: javascript