DEV Community

loading...

Discussion on: Don’t pay the for-loop tax

Collapse
theprash profile image
Prash

My argument has always been that writing a for loop that takes each element in an array, transforms it, and adds the output to another array, is writing your own implementation of map.

map is a well understood function these days that everyone can read so don't keep re-implementing it. It's just more code for you to own and read, and there's a chance of bugs in your implementation. To put it another way, you should use the map function for the same reason you use any functions at all: to avoid repeating code.

The same goes for filter and reduce.

RE performance: Measure it in the context of your application. I doubt there is a difference in the vast majority of cases given engine optimisations, but you can always fall back to a for loop where you can prove it's worth doing.

Collapse
forsakenharmony profile image
Leah

The funny thing is, writing your own map function with a for loop is faster than the native one (a plain for loop is still faster because it doesn't have to deal with the function invokations)