To calculate the sum of all numbers in an array, you could use a
Array.prototype.reduce() provides a shorter way to merge an array into a single value. This code does the exact same in fewer lines:
Every time the reducer-function is called, it saves its result to the accumulator. Going into our first calculation, the accumulator is set to the initial value. As
reduce steps through the array, it updates the current value with each of its entries in turn.
After going through all elements,
reduce returns the result of its last calculation.
The fallback “initial value”
When not given an initial value,
reduce uses the first element of the array as the initial value:
Instead of starting the calculation at
0, we skip a step and begin directly with
16. The result is the same, and our calculation requires fewer steps because it does not need to calculate
0 + 16.
Doing more than arithmetic
reduce can do more than basic calculations. We could also write a function that checks if every value in an array is above a certain threshold. Let’s say we want to write a function that returns
false if one person in a group is not older than 18 years. We set our initial value to
true and set our accumulator to
false as soon as one value does not match the condition:
If we didn’t set an initial value, reduce would use
16 as the accumulator’s default value:
Something is not right here. While one of the values is clearly not greater than 18, our function returns
We get this incorrect result because the assumed initial value of
TRUTHY_VALUE && OTHER_VALUE always returns
OTHER_VALUE. More importantly, the condition
16 > 18 is never evaluated in our faulty
If the values were ordered differently, we would not have noticed this bug. Let’s run the same function again, this time passing in
16 as the second value:
This calculation uses
23 as its initial value, which coincidentally meets the condition of being greater than 18. Again, this first condition of
23 > 18 is never evaluated! It’s pure luck that this call returns the expected result. The result of our function depends on the order of the elements in the array that is passed to it. That would be a terrible bug to track down.
It gets crazier. While the previous function checked if all values matched a certain condition, imagine we want to check if any values match it. We can replace the
|| to rewrite our function so that it checks if anyone is older than 18 years:
We no longer receive a Boolean value at all! Because of how
|| works, our function now returns the first “truthy” value it encounters, giving us
16 instead of either
Solving the problem by avoiding it
We could solve this problem by always passing an intial value to
reduce through its second parameter. However, there are several cases in which doing so wouldn’t be necessary. When running basic arithmetic, such as addition or multiplication, it is perfectly fine to use
reduce without specifying an initial value:
If we specified the initial value of
1, we would have to do an unnecessary calculation and still get the same result:
As we saw earlier, it is dangerous to not set an initial value if our reducer-function works with Boolean values. While we could make
Array.prototype.every() works like a
reduce-function that tests all entries against a condition. It always returns a Boolean value.
Not only does
every not require an initial value, the callback also does not use an accumulator. This makes it much easier to read and understand.
every checks if all elements in an array meet a condition, Array.prototype.some() checks if any element does:
This has all the same benefits as
every, without the pitfalls we ran into earlier.
The callbacks used in our examples for
some are identical, so we could even extract them to a shared helper function. If we contrast them with their
reduce-equivalents, we get much shorter and more readable code:
We could now use
isAnyoneOver18 exactly as we did before.
If you’re using
reduce to calculate Boolean values, see if you can rewrite them to the much simpler alternatives
some. They are better suited for situations in which
reduce can be a little problematic.
some have broad browser support, even being available in IE9.
There is more to learn
Get free previews of my upcoming course materials and other bonus content to help you work smarter. I share tips straight to your inbox once a week. You can read previous mails in the newsletter archive.
I respect your email privacy. Unsubscribe anytime.