JavaScript reduce()

Michael Abe
2 min readDec 9, 2021

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.

A great way to add everything up together in an array is to use the ‘reduce()’ method that is built into JavaScript. According to MDN web docs “The reducer walks through the array element-by-element, at each step adding the current array value to the result from the previous step (this result is the running sum of all the previous steps) — until there are no more elements to add.” So ultimately this has the potential to be a strong candidate to add up the total of our array.

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.

--

--