DEV Community

Discussion on: What s wrong with Array.reduce ?

Collapse
 
garretharp profile image
Garret

I think for loops are always king. However, reduce can actually be really nice in some cases, for example, you have an array of items in a cart and just want to list the total you can reduce the array and it looks really nice. I think reduce should be used in cases like this where you are just reducing an array down to something very specific like adding up all the numbers.

Collapse
 
functional_js profile image
Functional Javascript

And it's better to make a semantically rich utility function.

/**
@func
sum up an arr of nums

@param {number[]} a
@return {number}
*/
export const sum = a => a.reduce((acc, n) => acc + n, 0);

sum([1, 2, 3, 4, 5]); // 15
Enter fullscreen mode Exit fullscreen mode

P.S.
Although it might be tempting to extend the built-in Math namespace with a "Math.sum", that would be an antipattern to do so.