r/javascript • u/Anthony261 • Mar 20 '22
Are you using map, forEach, and reduce wrong?
https://antman-does-software.com/are-you-using-map-foreach-and-reduce-wrong36
u/RichardFingers Mar 20 '22
I don't agree with the argument that returning an array from reduce is inherently bad. Sure, if you are recreating existing operations using reduce, that's bad. But there are operations besides filter, map, etc. that result in an array where reduce is applicable.
16
Mar 20 '22
I agree. Combining operations as well. Example: you want to filter and map, you can do so in a single traversal using reduce, as opposed to traversing twice; once with filter and once with map.
3
3
u/gik0geck0 Mar 20 '22
I'm now curious, is there an observable performance difference between those?
15
Mar 20 '22
If you work with a very large data set then yes, traversing once has a significant advantage over twice. If it’s like 20 items then don’t bother. At a previous position we had to filter and transform arrays of objects streamed from a backend in batches of 50k to 250k. At that size if made a measurable and human noticeable difference.
4
u/FizzWorldBuzzHello Mar 20 '22
Honestly if you're working with larger sets like that you should switch to a lazy library that does not create intermediate arrays.
Make that library a part of your coding standard so your never have to think about it.
1
u/gonzofish Mar 20 '22
Yeah for small lists go for readability over performance. Unless you’re iterating over that small list constantly—I’m which case you should probably first think about how you can be iterating over it less
1
1
u/Kopikoblack Mar 20 '22
Could you provide an example code, I want to learn how to use reduce instead of using filter and map.
4
u/sfgisz Mar 20 '22
If it doesn't pass your filtering condition, return the array without pushing the item on it. If it passes, map and push the item before returning it. Can't type code on the phone, but that's all you need to do really.
1
u/bluehavana Mar 20 '22
Complexity wise, filter/map and reduce should be the exact same (other than creating intermediate arrays, which is key). Using a lazy library, like someone suggested would make the difference invisible.
4
u/weeeeelaaaaaah Mar 20 '22
Yeah, I get what he was going for but it was very poorly expressed. Just this week I wrote a tokenizer using reduce that took an array of characters and and returned an array of tokens but a single token often represents multiple characters. Can't use map for that!
1
u/bryku Mar 20 '22
I don't really get why they took that premise. Reduce is a powerful function in javascript. If people are confused about it, add an initial value. Then they can see what type it is.
1
u/IllegalThings Mar 20 '22
Yeah, and I can even think of cases where you’d want to use reduce in ways that’d result in a larger array. Decompression is the most obvious case. You could do it with map+flatten or just use reduce.
30
u/ogurson Mar 20 '22
Omg not only it's another boring map/foreach/reduce article, it also is annoyingly long and on top of that just plain wrong in some parts. I truly hate it.
4
u/Kablaow Mar 20 '22
It's also overly complex I think. If you have troubles knowing when to use which function I doubt this makes it clearer.
1
9
u/ImStifler Mar 20 '22
I like how js hipsters obsess about these kind of things instead of learning and discussing actual proper topics like what design patterns to use for problem x or learning about software architecture and development benefiting topics
3
u/gremy0 Mar 20 '22 edited Mar 20 '22
Map and reduce are fairly fundamental higher-order functions, in the abstract they provide a standardised pattern for solving problems and structuring code. In standard JavaScript arrays they allow for and are very often used with a method chaining paradigm.
You could consider this essentially equivalent to design patterns but functional, and since the solution to basically everything in functional programming is just more functions, they're just functions.
Understanding map and reduce properly is often non-trivial, particularly for beginners and people new to functional programming, yet it is somewhat essential, or the very least extremely useful for progressing in your understanding of it.
2
u/BasketAutomatic Mar 20 '22
My coworkers always use map instead of forEach and they never return anything. So annoying
5
1
u/euphocat Mar 21 '22
Use a linter. Eslint can forbid this behavior
1
u/BasketAutomatic Mar 21 '22
I do . But my coworkers either don't use eslint or disagree with its rules
1
0
u/redsandsfort Mar 20 '22
I just read some of this guys other articles. Some of them are really terrific. https://antman-does-software.com/stop-catching-errors-in-typescript-use-the-either-type-to-make-your-code-predictable.
-15
u/Accomplished_End_138 Mar 20 '22
If you are using forEach.. i will say.. Yes, you most likely are not using it right.
6
u/BluudLust Mar 20 '22 edited Mar 20 '22
For each is useful if you want to apply a common function on each element.
for (const element of anArray) { console.log(element); }Vs
anArray.forEach(a => console.log(a));Edit: log isn't the best example because it requires an arrow function. It prints a variable number of arguments, and without the arrow function it would use print all of (element, index, array).
-2
Mar 20 '22
anArray.forEach(console.log);5
u/BluudLust Mar 20 '22
Doesn't do what you expect. It'll log the element, it's index and the whole array separated by spaces.
5
1
u/GreatValueProducts Mar 20 '22
I strongly believe in this article especially in JavaScript: https://jakearchibald.com/2021/function-callback-risks/
-11
u/Accomplished_End_138 Mar 20 '22
Yeah. But not a very common thing in production code.
Plus, I would recommend you just use a console.table instead
2
u/BluudLust Mar 20 '22 edited Mar 20 '22
True. I used log as a mere example. And log isn't even a good example because it captures all parameters: (element, index, array)
If there was functionality you would have to retype in multiple loops using a single function and forEach is more proper.
1
u/Accomplished_End_138 Mar 20 '22
I find there are only a few things I do in operations that I don't expect and output.
console.table(myarray);Not a lot of code, plus gives a nice output of the results.
What other operation would you do in a foreach?
2
u/BluudLust Mar 20 '22 edited Mar 20 '22
Data processing.
anArray.forEach(doSomethingWithEachDataPoint);A very common example would be adding it to a graph, for example. You may have to use filter and map beforehand too.
anArray.filter(isValidDataPoint).forEach(addDataPointToChart);1
u/Accomplished_End_138 Mar 20 '22
So side effects, things that make code harder to test well, and i would avoid to keep the code base maintainable.
I normally would filter and add the array to the chart. Not adding each point.
A chart isn't generally useful until all data is displayed on it.
-1
u/Accomplished_End_138 Mar 20 '22
How often do you display charts with missing data?
1
1
u/Under-Estimated Mar 20 '22
To those who use forEach, may I ask why? I find for of clearer.
1
u/Accomplished_End_138 Mar 20 '22
Generally, I find people use it before learning other functions. Effectivly thinking it is cool when most of the time it is not better than a for of loop in how they use it.
Kimd of a babies first functional programming.
Honestly, it can be cleaner if re using the function. But I can't break like for if loop. And other operators would probably work better
-1
u/monsto Mar 20 '22
I have some usecases where I'm taking stuff from a number of different arrays and putting them onto things in like a master array.
And yes there are more clever ways to do this kinda thing, but I try to keep in mind that I'm the one that will have to come back to this proj in 3 mos and decipher what the fuck I was doing. So while a single for..of might do it, a bunch of separate forEach is way more readable.
0
u/astral_turd Mar 20 '22
Cool, time to head to refactor town then
-13
u/Accomplished_End_138 Mar 20 '22
Yeah.. It shouldn't be a big deal if the code is done well. Do you not write clean code that is easy to refactor?
20
u/astral_turd Mar 20 '22
No, I write shitty code that is hard to refactor.
-14
u/Accomplished_End_138 Mar 20 '22
I'm glad I don't work with you then. I require better from my developers
5
u/astral_turd Mar 20 '22
Is not using forEach one of the requirements?
-4
u/Accomplished_End_138 Mar 20 '22
No. But it is a bad practice since most of the time, they just didn't know better methods they could use before. And now they are quite happy learning and using them. I help them through it and explain why it helps long-term use and maintainability as well as how it helps testing.
2
u/fakehalo Mar 20 '22
Got yourself some of them strong and rigid opinions, I imagine the feeling is mutual.
1
0
-5
u/monsto Mar 20 '22
Where's the Typescript argument? I came here with popcorn to see a raging "typescript sucks" "no you suck" argument.
1
u/bryku Mar 20 '22
The other day I remade a project in typescript. It had a notable performance hit. From that point of view.. typescript sucks.
75
u/Justafa Mar 20 '22
Not really, why? Are you having difficulties?