Understanding Javascript Reducers

Understanding Javascript Reducers

What is actually happening when we call Array.reduce()?

What is a reducer?

The overwhelming example presented when learning "Reducers" is summing up an array of numbers. This results in thinking reducers are a one-trick pony. In fact, you can use an Array.reducer in place of many built-in Javascript array methods. We'll start with the dreaded "Summing up an array" example, and slowly pull back the curtain on Array.reduce(). sumValue.png When I was first learning reducers, this was the example used. My initial reaction was why would anyone ever do it this way? Let's break this code block down and step through it.

Let's start at the beginning, what is a reducer? Simply put, Array.reduce() calls a callback function (a reducer function) and calls it on every item in our array. Whatever is returned from our callback function (a reducer function) is saved, and updated on every iteration.

Array.reduce expects at least 1 argument, but it's most commonly called with 2. The first argument is our reducer function, the second is the initial value. This will make more sense as we refactor our code for clarity.

sumValue_V2.png

You'll notice a few things, first, our const initialValue = 0. Secondly, our function reducer(){}. These two arguments will be passed into our numbers.reduce(). Now let's step through what is actually happening when we call numbers.reduce(reducer, initialValue).

  • The reducer function will be called for every item in our numbers array.
  • The first time the function gets called, list = initalValue
  • Reducer function now returns 0 + currentNumber. On the first iteration, currentNumber = 1
  • The reducer function is now called again (It's called array * n times).
  • It now returns list + currentNumber, (1 + 2).
  • This continues until we reach the end of the array.

The reduce function now returns 1 value. In our example, it's 15. let total now points to that value. With some certainty, I know you're not closer to understanding Array.reduce. In our next "episode", we'll really start to use Array.reduce in a more practical (and less confusing) way.


Conclusion

Don't use Array.reduce() in order to get the sum total of an array. Throughout the series we'll continue to explore way's to use Array.reduce(). Stay tuned!

Now for a more succinct way of doing the same things.

forOfSum.png