Menu

1 / 2

Reduce Has Nothing To Do With Arrays

DEV Community: typescript·Amrishkhan Sheik Abdullah·6 months ago
#fCmNlxbb
#dev#state#enter#exit#article
Reading 0:00
15s threshold

Most developers think they understand reduce() .

They don't.

And to be fair, I didn't either for a long time.

Like many JavaScript developers, I learned reduce() through examples like this:

const total = [ 1 , 2 , 3 , 4 ] . reduce (( sum , n ) => sum + n , 0 )

console . log ( total ) // 10

Enter fullscreen mode

Exit fullscreen mode

Then I saw examples for:

grouping arrays

transforming arrays

creating lookup tables

counting occurrences

Eventually I came to the conclusion that:

Reduce is the Swiss Army Knife of array operations.

And while that statement is technically true, it completely misses the point.

Because the biggest misunderstanding about reduce() is this:

reduce() has almost nothing to do with arrays.

Arrays are merely where most developers first encounter the idea.

The real idea behind reduce() is much deeper.

Once you understand it, you start seeing the exact same pattern everywhere:

Redux

React's useReducer

RxJS scan

Event Sourcing

CQRS

State Machines

Financial…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.