How To Sum an Array Of Numbers In JavaScript – With Examples

There are three methods to sum an array of numbers in JavaScript.

Quick Answer: const sum = numArray.reduce((a, b) => a + b, 0);

This tutorial explains the different methods to sum an array and when it is appropriate to use each method.

Sum an Array Of Numbers Using Reduce(Simple Method)

The reduce() method executes a user-defined reducer callback function on each element of the array.

To sum the array of numbers using the reduce() method:

  • Pass the a+b as the user-defined function
  • Pass 0 as the initial value to the accumulator

The array must not have undefined items while using the reduce() method.

Use the reduce method when the array contains only numbers and you do not want to make any explicit checks on each array item.

Code

const numArray = [1, 2, 3, 4];

const sum = numArray.reduce((a, b) => a + b, 0);

console.log(sum);

Output

10

Sum an Array Of Numbers Using ForEach Method

The foreach() method iterates over each element in the array and applies a callback function or an arrow function into it.

During each iteration,

  • Check if the current item is a number
  • Add it to the sum.

Use this method when the array might have non-number items or undefined items.

Code

const numArray = [1, 2, 3, 4, undefined];

let sum = 0;

numArray.forEach(a => {
  if (typeof a === 'number') {
    sum += a;
  }
});

console.log(sum);

Output

10

Sum an Array Of Numbers Using Loadash Sum() Method

Loaddash is a modern JavaScript library that delivers modularity performance and other utility
functions. You can perform various operations by invoking the appropriate utility methods.

To sum an array of numbers in JavaScript, use the _.sum(array) method.

  • It provides the result after adding all the elements in the array.
  • This method also doesn’t support having character items or undefined items in the array.

Code

const numArray = [1, 2, 3, 4];

const total = _.sum(numArray);

console.log(total);

Output

10

Additional Resources

Leave a Comment