.reduce() method

My understanding is that in the examples provided, the parameters are being added because that is what we are inputting into our callback function. Does the .reduce() method always add the values together, or can it also be used to combine parameters in a different way?

You can define your own functionality. It doesn’t have to be addition, it can be multiplication or subtraction, for example.

//modified reducer from MDN example to multiply instead
const array = [1, 2, 3, 4];
const reducer = (previousValue, currentValue) => previousValue * currentValue;
console.log(array.reduce(reducer)); //prints 24

For a more defined reference, check MDN docs: Array.prototype.reduce() - JavaScript | MDN

1 Like

To add onto pitabread’s answer (well, not in terms of quality), here’s a little…diagram: