Sum of an Array in JavaScript

To get the sum of all values in an array in JavaScript, use either a for loop or the reduce() method. In this tutorial, we will learn how to use both approaches so you can decide which one best fits your scenario.

 

for Loop Array Sum

With a for loop we can iterate through the array and add each value to a sum variable like this:

 

let numbers = [5,4,8,12];
let sum = 0;

for (let i of numbers) {
sum += i;
}

console.log(sum);
29

 

reduce() Method Array Sum

The reduce() method in JavaScript loops through iterables and keeps an accumulator. Therefore we can use it to get a sum of all the elements in an array like this:

 

 

let numbers = [5,4,8,12];

const reducer = (accumulator, curr) => accumulator + curr;

let sum = numbers.reduce(reducer);

console.log(sum);
29

 

Read a more detailed overview of how the JavaScript reduce method works.

array