Categories
JavaScript Answers

How to reduce an empty array with JavaScript?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *