Reduce is Not the Answer

May 28, 2023

TLDR

The reduce function:

reduce is the for-loop of functional programming…

What is reduce?

The reduce function takes a collection, iterates over it, and generates a single value.

Depending on the language, it might also be called: fold, accumulate, aggregate, compress, or inject.

// a quick JavaScript example
> [1, 2, 3, 4, 5].reduce((acc, x) => acc + x);
15

If you’re not already familiar with reduce, let me punt to Google.

What’s the problem?

reduce is just a for-loop, with some “accumulator”. When the accumulator is a list/map, things can get complicated pretty fast.

Here’s a for-loop:

function doSomething(arr) {
  let acc = [];

  for (let value of arr) {
    // complicated code
  }

  return acc;
}

And here’s the same code as a reduce:

function doSomething(arr) {
  return arr.reduce((acc, value) => {
    // complicated code
  }, []);
}

What COULD this code do? 🤔

Anything, really.

It could be a map or a filter, or some terrible combination of both or neither.

My Point: reduce is too low-level

A for-loop can do anything and reduce has the same lack of clarity and intent… because it is a building block:

Reduce (sometimes called fold) is a basic building block in functional programming. Almost all of the functions in the Enum module can be implemented on top of reduce. 1

But a pile of building materials is not a house.

A reduce, given an anonymous function, is similar to tricky, inlined, and uncommented code. It’s a missed opportunity to extract that logic to a function and give it a name.

But first…

Alternatives

That reduce is probably not a special case, and it’s probably one of these:

If you use a functional language 2, refer to its excellent “enumerable” module:

What’s Next?

In my next post 3, I’m going to cover reduce anti-patterns.


  1. This is a typical homework assignment. 

  2. If missing, email me your own language’s link 

  3. Coming soon… 

Discuss on Twitter