For more tips like this, sign up to the weekly newsletter!
Use the initialValue
argument of reduce
Array.reduce
's second argument is an optional initial value. Based on whether it's supplied or not, there are three cases:
- If
initialValue
is set, it will be the firstaccumulator
- If
initialValue
is not set, the first element will be the firstaccumulator
- If
initialValue
is not set and the array is empty, an error is raised
The initialValue
is usually considered the "zero element" of the operation defined in the callback. A few examples:
- For addition, it's
0
- For multiplication, it's
1
- For array concatenation, it's
[]
But not all operations have a zero element.
This code throws an error if the array is empty:
array.reduce((acc, e) => acc + e);
Avoid this error case by defining an initial value, if there is an applicable one. The following code returns 0
for the empty array:
array.reduce((acc, e) => acc + e, 0);