As we have discussed many times, as a basic fundamental aspect of programming, we use a lot of arrays to hold and potentially manipulate data. A common type of data that we would add to an array is numbers. Obviously, when dealing with numbers one of the things that we commonly want to do is add them up. Adding the up an array of numbers could reasonably assume that at some point, one of the things that you may want to do with the array is to add everything together.
The doc goes on to explain that the ‘reduce()’ method “executes a user-supplied “reducer” callback function on each element of the array, in order, passing in the return value from the calculation on the preceding element. The final result of running the reducer across all elements of the array is a single value.” Ultimately we have to provide a function and pass it to the ‘reduce()’ method as an argument that gets called over and over for the duration of the array. In our case we want to add the elements in our array and continue that for perpetuity.
In the example above, we are simply setting the variable to “array”. In the second line, we are creating a function that we will be passed to our reducer. The “addTotal” function takes two arguments “previousValue and currentValue” and returns the total of the two. As this function is called over and over again we are effectively adding the total of the array index by index. This is a great way to use a callback function index by index without writing a for loop.