How to Find the Sum of an Array of Numbers

There are multiple ways that you should use in order to calculate the sum of an array of numbers. Let’s discuss each of them and try examples.

reduce()

You can use the reduce() method to find the sum of an array of numbers.

The reduce() method executes the specified reducer function on each member of the array resulting in a single output value as in the following example:

let arr = [10, 20, 30, 40];
let sum = arr.reduce(function (a, b) {
  return a + b;
}, 0);
console.log(sum); // Output: 100

The 0 in is the default value. If default value is not supplied, the first element in the array will be used. If the array is empty, you will get an error.

If you use ES2015, you can make it more verbose like this:

const sum = [10, 20, 30].reduce((a, b) => a + b)
console.log(sum); // Output: 60

for loop

Another fast method is using for loop which is even faster as the reduce() method:

let numbers = [10, 20, 30, 40, 50]
let sum = 0;
for (let i = 0; i < numbers.length; i++) {
  sum += numbers[i]
}
console.log(sum) // Output: 150

forEach loop

An alternative way of calculating the array of numbers is using forEach loop like this:

const arr = [10, 20, 30, 40];
let result = 0;
arr.forEach(number => {
  result += number;
})
console.log(result); // Output: 100

The reduce() method

The reduce() method invokes a reducer function provided on each element of the array and results in single output value. It executes the callback once for each assigned value present in the array taking four arguments: accumulator, currentValue, currentIndex, array. It is recommended to provide default value such as 0 for performing addition and 1 for performing multiplication.

Do you find this helpful?

Related articles