There are a number of different strategies that can be used to loop over JavaScript arrays.
So far in this course, we have discussed three special array methods that allow you to do this: the forEach
method, the map
method, and the filter
method.
In this tutorial, you will learn how to use the JavaScript reduce
method, which provides a fourth way to loop over JavaScript arrays.
Table of Contents
You can skip to a specific section of this JavaScript reduce
method tutorial using the table of contents below:
- How to Use The JavaScript
reduce
Method - The Differences Between the
map
,filter
, andreduce
Methods in JavaScript - Final Thoughts
How to Use The JavaScript reduce
Method
The JavaScript reduce
method is one of the more complicated array methods in the JavaScript programming language because it contains so much functionality. However, once you fully understand how it works, the reduce
method is very useful.
The reduce
method executes a function (called the reducer
function) on every element of the array. The reduce
function is different from other array methods (like map
) in that it only results in a single value.
The Mozilla Developer Network provides an excellent example of how the reduce
method works. I have included the example below.
const array1 = [1, 2, 3, 4];
const reducer = (accumulator, currentValue) => accumulator + currentValue;
// 1 + 2 + 3 + 4
console.log(array1.reduce(reducer));
// expected output: 10
// 5 + 1 + 2 + 3 + 4
console.log(array1.reduce(reducer, 5));
// expected output: 15
In the first console.log
method in the code block, the reducer
function is used to easily calculate the sum of the items in array1
.
In the second console.log
method, the reducer
function is used to add all of the items in array1
as well as the integer 5
.
The reason why 5
is included as an argument in the reduce
method is because reduce
actually accepts a second argument that specifies which number you'd like to start the reducer
function at. We will see more examples of this later in this tutorial.
As you can see, the reduce
method actually reduces the size of the array as it performs its operation. This is a useful way to remember its functionality without having to test it on a real JavaScript array.
Let's consider a few more examples of the reduce
method to make sure you full understand its powerful functionality.
Examples of the JavaScript reduce
Method
I will now work through several examples of how you might use the reduce
method while developing JavaScript applications. Please keep in mind that these examples are not exhaustive - there are many more ways you could use reduce
that will not be covered in this tutorial.
Example 1: Calculating Sum While Printing Sum To Console
Earlier in this tutorial, we saw an example from Mozilla Developer Network that used the reduce
method to add each item in a JavaScript array. I'm going to rebuild this functionality from scratch with one added feature - the reducer
function will print the current tally of the reducer
function using the console.log
method each time it iterates over a new item in the array.
We'll be using the following array for this example:
const integers = [1, 2, 3, 4];
To start, we need to build the reducer
function, which we will call addItems
. It will take two arguments.
We will call the first argument item
, and since this is a reducer function, the second argument will be called currentSum
.
Here is how we would write this function:
function sumReducer(item, currentSum){
newSum = currentSum + item
console.log(newSum)
return newSum;
}
We can now apply this function to every item in the integers
array using the reduce
method, like this:
const integers = [1, 2, 3, 4];
function sumReducer(item, currentSum){
newSum = currentSum + item
console.log(newSum)
return newSum;
}
integers.reduce(sumReducer, 0);
Note that as before, we need to include the second argument of 0
in the reduce
method to show that the currentSum
variable should be initialized at 0
.
Example 2: Calculating The Product of Every Item in an Array
Just like we can use the JavaScript reduce
method to add every item from an array, we can also use it to multiply array items together. Let's multiply together every item from the integers
array that we used previously:
const integers = [1, 2, 3, 4];
First, we need to create a function called productReducer
which accepts two arguments and multiples them together. Since this function will be used as the reducer
function in our reduce
method, we will call the second argument currentProduct
.
function productReducer(item, currentProduct){
return currentProduct *= item;
}
We can now apply this function to every item in the integers
array using the reduce
method, like this:
const integers = [1, 2, 3, 4];
function productReducer(item, currentProduct){
return currentProduct *= item;
}
integers.reduce(productReducer, 1);
Note that in this case, the initial value of the currentProduct
variable should be 1
and not 0
as 1
is the base unit for multiplication (just like 0
is the base unit for addition and subtraction).
Example 3: Concatenating an Array of Strings
For our last example, I will show you how you could concatenate together an array of strings using the JavaScript reduce
method. Here is the array of strings that we will be working with:
const strings = ['Nick', 'is', 'a', 'software', 'educator'];
As before, we will start by building our reducer
function, this time called stringReducer
. It's two variables will be called item
and currentString
. Here's how you would write it:
function stringReducer(item, currentString){
return currentString = currentString.concat(item);
}
Lastly, we will invoke the productReducer
function within the reduce
method:
const strings = ['Nick', 'is', 'a', 'software', 'educator'];
function stringReducer(item, currentString){
return currentString = currentString.concat(item);
}
strings.reduce(stringReducer, '');
There are a few things you should note about this last example:
- The
reduce
method should be invoked with an initial value of''
- an empty string - This code doesn't automatically add spaces between the words. You could make the following modification to fix this:
const strings = ['Nick', 'is', 'a', 'software', 'educator'];
function stringReducer(item, currentString){
return currentString = currentString.concat(` ${item}`);
}
strings.reduce(stringReducer, '');
The Differences Between the map
, filter
, and reduce
Methods in JavaScript
Given their similar functionality, it can be difficult to remember the differences between the map
, filter
, and reduce
methods in JavaScript.
I find that referring back to this useful visualization can be very useful:
Note - this photo doesn't contain actual JavaScript code, but has been generalized to be understood by developers working in any programming language. The map
, filter
, and reduce
methods are included in essentially every modern language.
Referring back to this image should prove helpful when you're adding map
, filter
, or reduce
methods to your JavaScript applications in the future.
Final Thoughts
In this tutorial, you learned how to use the JavaScript reduce
method.
Here is a brief summary of what was discussed in this lesson:
- How to use a JavaScript
reduce
method - The purpose of the second argument of the
reduce
method - it tells thereducer
function what initial value to use - A few examples of the JavaScript
reduce
method in practice - The differences between the
map
,filter
andreduce
methods in JavaScript (or any other programming language)