All code using
Array.prototype.reduceshould be rewritten without it so it’s readable by humans.
This claim started a great discussion on X and inspired me to summarize what I think in this article.
The problem with
Array.prototype.reduce is mainly with readability, though
some developers like myself generally prefer the functional approach over
control structures such as
for…of. So let’s see an example using both methods:
I’m cheating a little bit with this example because some of the few scenarios in
Array.prototype.reduce is more readable are sums and products. Let’s try
another example, this time with a more complex operation:
Array.prototype.reduce isn’t always the most readable, and even if we didn’t
cared about readability, we also have to consider that the performance is
worsened in this case because, to keep it immutable, we are creating a new
object in every iteration. One other limitation of
that it only works with arrays, while
for…of works with any iterable.
My suggestion to keep the syntax “functional”, while gaining the benefits of
for…of is to create a simple function that uses
for…of under the hood, but
which external interface is similar to
We could also use libraries such as immer to go the other way around and write code that has “mutation ergonomics” without the mutations: