r/coding • • Feb 26 '20

JavaScript: Array Reduce Explained in 80 Seconds

https://youtu.be/lxT4LZdtJrU
117 Upvotes

8 comments sorted by

View all comments

9

u/[deleted] Feb 27 '20

.reduce is the swiss army knife of all js array methods, it's my favourite. Your readability takes a bit of a hit, so I try not to be too convoluted with it, but it is always really fun to flex its muscles every now and again.

If you find yourself chaining array methods .reduce can almost always do the work of 2 or more of them at once.

7

u/Kache Feb 27 '20 edited Feb 27 '20

Reduce should really only be used for "accumulation" operations. Sneakily doing other things with it only serves to make code misleading and confusing.

Edit

So, reduce use-cases:

  1. Intended: accumulating a value type, i.e. binary operator folding

  2. Not: Associating a mutable object/state with each element, instead use each_with(obj) that some languages have, or just a normal loop

  3. Not: just using for looping

5

u/[deleted] Feb 27 '20

I agree in general (which I said in my post) but also generally try not to follow arbitrary rules like that.

I never do anything 'sneakily'. If a one line comment will save an extra loop or 2 through an array, especially if the size of which is unknown, I'll make the case for .reduce any day.

1

u/Durdys Feb 27 '20

Chrome team even have a video on it: https://youtu.be/qaGjS7-qWzg

1

u/[deleted] Feb 27 '20

I've seen that video before. While I don't really agree with it, I'll concede that those guys are definitely smarter than I am

1

u/NoahTheDuke Feb 27 '20

You mean side effects? What else would be considered “sneakily”?