DEV Community

Discussion on: You don't need Array.reduce()

Collapse
 
joelnet profile image
JavaScript Joel • Edited

for loops either mutate data or perform side effects, which as a general rule why they are good to avoid.

map, filter, and reduce also allow better code reuse and testability because it can be broken down further than a for loop can.

Example:

// modular, reusable, testable!
const add = (a, b) => a + b

// readable!
const sum = array.reduce(add)
Enter fullscreen mode Exit fullscreen mode

You'll also notice all those lets go away and become const.

Get rid of for loops and it's possible to write your entire program without a single var or let!

Collapse
 
crazy4groovy profile image
crazy4groovy

I think you mean

const add = (a, b) => a + b
const sum = array.reduce(add, 0)

You need a seed value.

Collapse
 
joelnet profile image
JavaScript Joel

Nope. That is exactly what I meant.

The seed is optional. If you don't provide a seed, the first item in the array is given as the accumulator.

Run the code!

const add = (a, b) => a + b

[1, 2, 3].reduce(add) //=> 6
Enter fullscreen mode Exit fullscreen mode
Thread Thread
 
fregante profile image
Fregante • Edited

Sum is just about the only case where reduce is useful, but in reality it should never be passed around like that. Why keep an add function around that is only meant to be used together with a reduce? Just wrap it once and never use reduce again:

const sum = (array) => array.reduce((a, b) => a + b);

sum([1, 2, 3]) //=> 6
Enter fullscreen mode Exit fullscreen mode

Don't tell me arr.reduce(add) makes more sense than sum(arr) because it doesn't.

In reality you can write sum event more efficiently with a regular loop and every part of your code benefits.

Collapse
 
elitelabyrinth profile image
Average Joe

But if you don't pass any initial value then there would be errors in case of empty arrays. Example:

Image description