Summing An Array In JavaScript: A Guide To The Reduce(), For Loop, And ForEach() Functions

In this tutorial, we will cover several methods for summing the values of an array in JavaScript, including the reduce() function, the for loop, the forEach() function, and the spread operator with the Math.sum() function. We will also provide examples for each method, so you can see how they work in practice. Whether you are a beginner or an experienced developer, this tutorial will have something for you. So let's get started!

Using reduce() function

One of the most common methods is to use the reduce() function, which iterates through the array and accumulates the result of a callback function applied to each element. Here is an example of using the reduce() function to sum the values of an array:

const numbers = [1, 2, 3, 4, 5];

const sum = numbers.reduce((accumulator, currentValue) => accumulator + currentValue, 0);

console.log(sum); // Output: 15

Using for loop

Another way to sum the values of an array is to use a for loop:

const numbers = [1, 2, 3, 4, 5];

let sum = 0;

for (let i = 0; i < numbers.length; i++) {
  sum += numbers[i];
}

console.log(sum); // Output: 15

Using forEach() function

The forEach() function can also be used to iterate through an array and perform a specific action on each element. Here is an example of using the forEach() function to sum the values of an array:

const numbers = [1, 2, 3, 4, 5];

let sum = 0;

numbers.forEach(function(number) {
  sum += number;
});

console.log(sum); // Output: 15

Using spread operator and Math.sum() function

Another option is to use the spread operator (...) with the Math.sum() function, like this:

const numbers = [1, 2, 3, 4, 5];

const sum = Math.sum(...numbers);

console.log(sum); // Output: 15


No matter which method you choose, the result will be the same: the total sum of the values in the array.