Categories
JavaScript Answers

How to find the sum of an array of numbers with JavaScript?

Spread the love

To find the sum of an array of numbers with JavaScript, we call the reduce method.

For instance we write

const sum = [1, 2, 3].reduce((partialSum, a) => partialSum + a, 0);
console.log(sum);

to call reduce with a function that returns the partialSum plus the number a in the array being looped through.

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

The sum is returned and it’s 6.

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 *