How to use the JavaScript reduce() Method
The JavaScript reduce()
method provides a clean way to loop through an iterable and do something with each value in a function. It works in a similar way to a for
loop except it handles accumulation and the current value/index allowing the code to be easier to read.
In this tutorial, we will learn how to use the JavaScript reduce()
method using examples.
The reduce() Syntax
The JavaScript reduce()
method passes four arguments to a user-defined function defined as the first argument and an optional initial value as a second argument. Let's take a look at the syntax and examine what each part does.
array.reduce(function(total, currentValue, currentIndex, array), initialValue)
total
– (required) this will be the value of the first element of the array on the first iteration and the value of the returned value from the function in subsequent iterations.currentValue
– (required) the value of the element on the current iteration.currentIndex
– (optional) the index of the current iteration.array
– (optional) the input array.initialValue
– (optional) the initial value to start reduce() on. If this is argument is not supplied reduce will start with the value of the first element in the array.
Adding Values in an Array using reduce()
Let's begin by creating a function that will get the sum all the values in an array using the reduce()
method.
var nums = [5, 10, 15, 20];
var output = nums.reduce(countNums);
function countNums(total, currentValue) {
return total + currentValue;
}
console.log(output);
50
In the example above the total on the first iteration is equal to the first element on the array. This is added to the current value which on the first iteration is the second array element and returned to reduce()
as the total ready for the next iteration.
As a side note let's write the same functionality as above with a for loop to compare how readable each different approaches are.
var nums = [5, 10, 15, 20];
var output = 0;
for (let i of nums) {
output += i;
}
console.log(output);
50
The readability of both approaches are comparable for getting the sum of values in an array, but for more complex functions reduce()
would probably be the cleaner choice.
Specifying an Initial Value
As mentioned earlier in the article if an initial value is not set the first total will be from the first index of the array. We can change this behaviour by setting an initial value. Let's try another example by setting the initial value of reduce()
at 6
.
var nums = [5, 10, 15, 20];
var initialVal = 6;
var nums = [5, 10, 15, 20];
var output = nums.reduce(countNums, initialVal);
function countNums(total, currentValue) {
return total + currentValue;
}
console.log(output);
56
Conclusion
You now know how to use the JavaScript reduce()
method and when it might be a better way to achieve a task over more conventional approaches.