Array.prototype.reduce() in Javascript ES6

Yoel Macia
The Javascript Adventure
2 min readDec 3, 2019

The other day when i was writing an article for the Rest Operator one friend told me than one of my examples can be simplify by a function call reduce().

Photo by Markus Spiske on Unsplash

Here is the example in question,

const multiply = (...args) => {
let result = 1;
for (let i in args) {
result = result * args[i];
}
return result;
};
multiply(2,2,2) // 8

I will try to use reduce() and simplify the example above, to make it even clearer.

Function reduce():

The Array.reduce() method executes a reducer function (which we provide) in each element of the array, resulting in a single output value.

So before using it, we have to define our reducer() function, which will have two arguments (accumulator, currentValue).

The accumulator argument is the value we end up with.
The currentValue argument is the action we are going to perform to get to a single output value.

Defining the reducer() function,

const reducer = (accumulator, currentValue) => { 
return accumulator * currentValue;
};

Array.reduce() takes two arguments (callback, initialValue)

The callback is our reducer() function.
The initialValue is optional, the default value is 0.

Rewriting our multiply function, the callback is the reducer() function then we define before, the initial value is 1 because we want to multiply for 1 in the first iteration, if we multiply for 0 the whole result will be 0.

let multiply = (...args) => 
args.reduce((accumulator, currentValue) => {
return accumulator * currentValue;
}, 1);

We can simplify it even more by calling the reducer() function directly.

let multiply = (...args) => args.reduce(reducer, 1);

The reduce() function its super simple, makes your code more clean and simplify the uses of arrays.

Thank you very much and keep coding!!!

Yoel

I often share more code tips on my Instagram you can say hello to me on my Twitter or see how i code in my Github.

--

--

Yoel Macia
The Javascript Adventure

Writing daily about Javascript. Creator of the publication The Javascript Adventure.