The reduce() method—like the method we covered in the previous week—is a higher-order function that is designed to solve a common problem. This video goes over a list of elements and how to retrieve a single value related to them.
So we don't need to create a separate variable. We just assign the results of the reduce function into the variable that we want. Now, typically, what we include in this callback is an incrementer, as well as each individual item that we're going to be going through. In this case, the incrementer would be the result of the addition of each of these items. So the first time this runs, the value of this incrementer is going to be two. The second time, it's going to be two plus three, which'll be five.
And then it will be nine, et cetera, et cetera. As it goes through this function, it'll just keep on incrementing and returning those values. The item value will have the value of each of the elements in the array as we loop through them. Now, the result of all those additions are going to be stored in this total variable, and then we can easily output that. Now, as I mentioned, reduce is a higher-order function. So, because it returns a value, you can use them with other higher-order functions, like map, and combine them into a series of different methods, like this right here.
So here, we've actually extracted this function that we are calling now addEm, and addEm can be referred to like this. Instead of a callback inside the reduce method, we can sort of refer to that as a separate function. And since we are using this map method, we can actually queue them up and change the original array using the map function and then use reduce to reduce the results of the map into a single value.
Now, in this case, the result is going to be 25 because we're adding one to each of these numbers first and then we're reducing them by adding the numbers together. So we could do that sequentially, like this. Now, for simple methods, these functions, like inc and addEm, are usually expressed in the newer ES6 arrow notation. So you could see what we're doing here is the same thing we were doing before with a function. But we're actually creating the variable first, and then we're using arrow functions to hold the value of the methods that we want to create.
And, as usual, if you have any ideas for this weekly series, and maybe you want to share with me some questions you've been asked or have asked in interviews, connect with me on LinkedIn or just about any social media network, like Twitter or GitHub, @planetoftheweb.
Skill Level Intermediate
Q: Why can't I earn a Certificate of Completion for this course?
A: We publish a new tutorial or tutorials for this course on a regular basis. We are unable to offer a Certificate of Completion because it is an ever-evolving course that is not designed to be completed. Check back often for new movies.