How to Fix TypeError: Reduce of empty array with no initial value

The TypeError: Reduce of empty array with no initial value error occurs in JavaScript when you call the reduce() function on an empty array without providing an initial value.

To fix the TypeError: Reduce of empty array with no initial value error, you must provide an initial value as the second argument to the reduce() method.

Message

TypeError: Reduce of empty array with no initial value

Error type

TypeError

What went wrong?

The reduce() method needs an initial value when applied to an empty array. When we don’t provide an initial value, it will throw the TypeError: reduce of empty array with no initial value.

The array.reduce() is a built-in method used to reduce an array to a single value by applying a provided function to each element in the array and returning the accumulated value.

This error is raised when an empty array is provided because no initial value can be returned.

Examples

Invalid case

const numbers = [];

const sum = numbers.reduce((acc, cur) => acc + cur);

console.log(sum);

Output

TypeError: Reduce of empty array with no initial value

In the above code, we created empty array numbers and tried to use the reduce method without providing an initial value. It will result in the “TypeError: reduce of empty array with no initial value” error because the reduce() method requires an initial value when applied to an empty array.

Valid case

The below code is a valid case!

const numbers = [];

const sum = numbers.reduce((acc, cur) => acc + cur, 0);

console.log(sum);

Output

0

After providing the second argument 0 to the reduce() function, you can see that it compiler does not throw any error and returns 0 as output because the array is empty.

That’s it for this example.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.