Categories
JavaScript Answers

How to sum up an array in JavaScript?

Spread the love

To sum up an array in JavaScript, we use the reduce method.

For instance, we write

const sum = array.reduce((pv, cv) => pv + cv, 0);

to call array.reduce with a callback that returns the sum between partial sum pv and the current value cv.

We set the initial sum value to 0 with the 2nd argument.

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 *