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…