To reduce an empty array with JavaScript, we should set the initial value returned by reduce
.
For instance, we write
const val = [].reduce(
(previousValue, currentValue) => previousValue + currentValue,
0
);
to call reduce
on an empty array with a callback that returns the partial sum of the array values.
We set the initial value of previousValue
to 0 by calling it with the 2nd argument to avoid the reduce empty array error.