DEV Community

Discussion on: What s wrong with Array.reduce ?

Collapse
 
vonheikemen profile image
Heiker

There is nothing wrong with reduce, it's only sin is to be slightly more difficult to understand than a for loop. The arguments against reduce can be reduced to this phrase.

I can do this with a for loop.

That's it. Anything that you can do with reduce you can do with a for loop, but since the for loop is the "simpler more readable" choice then it must be the right one.

Collapse
 
cullophid profile image
Andreas Møller

In this case simpler and more readable is very subjective.

Collapse
 
chidioguejiofor profile image
Chidiebere Ogujeiofor

Is it not safe for us to say that once you understand how the reduce function works, then reading/understanding it becomes quite easy.

I agree that the loops are more readable though but I don't think it's enough to tell folks 'never' to use reduce

Collapse
 
dvddpl profile image
Davide de Paolis

Agree. Readability is anyway mostly a matter of being used to read such code. :-)

Collapse
 
vonheikemen profile image
Heiker

That's why it's wrapped in quotes.

Collapse
 
dvddpl profile image
Davide de Paolis

mmm. but this is true also for array.foreach and array.map etc. and i find those much nicer and simpler. I love reduce. but i kind of agree with the rant in the tweet to some extent

Collapse
 
vonheikemen profile image
Heiker

I'm just repeating the only argument against reduce I think it make sense. By some misfortune reduce doesn't seem to "click" with people in the same way map, filter or forEach do.

Thread Thread
 
jbristow profile image
Jon Bristow

which is a shame, because map, filter, and forEach are just reduce in disguise.

Thread Thread
 
alainvanhout profile image
Alain Van Hout

Though, for completeness, all of those are just loops in disguise (which isn't an argument for or against it).

Thread Thread
 
jbristow profile image
Jon Bristow • Edited

Only if you consider loops and tail recursion to be the same thing, which is debatable.

Also, it's only the same when applied to lists.

Other monadic structures may not act as loops at all, when called with reduce aka fold