Sometimes, we may run into the ‘TypeError: Reduce of empty array with no initial value’ when we’re developing JavaScript apps.
In this article, we’ll look at how to fix the ‘TypeError: Reduce of empty array with no initial value’ when we’re developing JavaScript apps.
Fix the ‘TypeError: Reduce of empty array with no initial value’ When Developing JavaScript Apps
To fix the ‘TypeError: Reduce of empty array with no initial value’ when we’re developing JavaScript apps, we should make sure that we’re calling the Array.prototype.reduce method with an initial value.
For instance, if we have:
const ints = [0, -1, -2, -3, -4, -5];
ints.filter(x => x > 0)
.reduce((x, y) => x + y)
then we get the error since we didn’t pass in a 2nd argument to reduce.
So the x parameter in the reduce callback is set to undefined and the callback fails to run.
To fix this, we write:
const ints = [0, -1, -2, -3, -4, -5];
ints.filter(x => x > 0)
.reduce((x, y) => x + y, 0)
to pass in a 2nd argument to reduce.
Then x is set to 0 and that’s returned since filter returned an empty array.
Conclusion
To fix the ‘TypeError: Reduce of empty array with no initial value’ when we’re developing JavaScript apps, we should make sure that we’re calling the Array.prototype.reduce method with an initial value.