How the reduce() method works in JavaScript

Written by
Published on

One of the built-in Array methods that I rarely see used in production code is the relatively new (ES6) reduce() method.

Like with many of the built-in methods found in the Array object in JavaScript, the reduce() method isn't required for any particular task. But it can be very useful in a few scenarios in terms of reducing the amount of code needed to accomplish certain tasks.

Let's take a look at how it works.

How does it work

The main role of the reduce() method is to loop through a given array, and to perform a cumulative operation ("reducer") on each of the values in that array.

Essentially, you calculate a value during each phase of the loop for each item, and you then return that value to the next phase of the loop, until you run out of array elements. In which case, that final value returned is the result of the reduction.

Here's what it looks like in action before we break down the components.

let nums = [1, 2, 3];
let result = nums.reduce(function(previousValue, currentValue, currentIndex, array) {
  return previousValue + currentValue
}, 0);
console.log(result); // 6

The reduce() method can be called on any given array object and it takes in 2 arguments, a callback function and an initial value to set the reduction to. More on that below.

The syntax

The full method signature of the reduce() method is as follows. This version uses the ES6 syntax for an arrow function.

array.reduce((previousValue, currentValue, currentIndex, array) => { ... }, initialValue)

You can also always specify an inline callback method instead as well:

array.reduce(function callbackFn(previousValue, currentValue, currentIndex, array) { ... }, initialValue)

Note that not all of the parameters are required in order for a basic reduction to work. A callback function is required, and the previousValue and currentValue parameters inside of that callback is also required.

The remaining arguments (to both the reduce() and the callback) can be beneficial however in some cases.

Function Arguments

The reduce() method itself takes in 2 arguments, as mentioned above.

- A supplied callback function (inline or arrow function) that operates on every element in a given array.

- An optional initial value that initializes the previousValue argument (in the callback method) during the first initial iteration.

If no initialValue was supplied, then previousValue will be equal to the first value in the array and currentValue will be equal to the second. Confusing, I know.

To be on the safe side, I typically always try and initialize the initial value to some default.

Callback Function

The callback function that the reduce() method takes, contains 4 different parameters, the last 2 being optional.

array.reduce(function callbackFn(previousValue, currentValue, currentIndex, array)...

- previousValue - the value returned from the previous callback function call.

- currentValue - the current value in the array being looped

- currentIndex - the index of the current iteration in the array (optional)

- array - the array object being reduced (optional)

If the initial value is passed in to the reduce() method, on the first initial run, the previousValue parameter will be set to that value.

If no initial value is set, however, then previousValue will be set to the first item in the array, and the currentValue to the second item in the array.

The 4th argument, array, is useful when working with an undeclared array, as follows.

[1, 2, 3].reduce(function(prev, curr, index, array){return prev + curr});

The array argument gives us access to the array being iterated through.

Return statement

The value that is returned inside of the callback function of the reduce() method, is the same value that will get set as the previousValue argument for the next iteration of the loop.

Take the following code as an example:

[1, 2, 3].reduce(function(prev, curr, index, array){return prev + curr}, 0);

In this particular case (with the given array), the loop would render the following values:

index previousValue currentValue
0 0 1
1 1 2
2 3 3

The final return statement in this case would be equal to the final previousValue added to the currentValue.

Last words

The reduce() method isn't the easiest to get used to, as you might have guessed. And that's mainly because it has alot of moving parts and because the logic isn't very intuitive as it is with other built-in methods.

But when used correctly, such as in summations or flattening arrays, it can save you a substantial amount of lines of code and can even help with performance at times.

Walter Guevara is a software engineer, startup founder and currently teaches programming for a coding bootcamp. He is currently building things that don't yet exist.


No messages posted yet

Developer Poll 🐱‍💻


Add a comment

Send me your weekly newsletter filled with awesome ideas