DEV Community

Cover image for Why I don't like reduce

Why I don't like reduce

Dominik D on January 12, 2021

The popular eslint-plugin-unicorn recently added a no-reduce rule, and it is set to error per default. The argument is that Array.reduce will likel...
Collapse
 
madza profile image
Madza • Edited

I need to look up it's syntax every time I use it πŸ˜€πŸ˜€

arr.reduce(callback( accumulator, currentValue, [, index[, array]] )[, initialValue])

Collapse
 
metalmikester profile image
Michel Renaud

When I saw the title of the article my first thought was, "right... how does that thing work again?" It's one of those things that I'm unable to memorize and always have to look up.

Collapse
 
vonheikemen profile image
Heiker

I would like to add to that reduce is very good with binary operations that are closed under one type. Like "add" where you have (Number, Number) -> Number. The kind of functions where you don't even care who is an accumulator and what's the current value. You just plug it like this arr.reduce(binary_op) and you're done.

Collapse
 
tkdodo profile image
Dominik D

yes, summing two numbers is a classical example for reduce. It's actually reasonable because it really "reduces" the input into one value. I still prefer to use a util function for readability, like sum(numbers). Can be taken from lodash, but can also be just my own util that implements it with reduce. The name alone is worth the abstraction that I don't have to read reduce a bunch of times and have to grasp the implementation :)

Collapse
 
havespacesuit profile image
Eric Sundquist

In general it is difficult to read, which is a good reason not to use it. If a simple for iteration gets the job done, your teammates will probably thank you.