How to Find the Sum of Array of Integers in JavaScript?

Using Array.prototype.reduce()

Introduced in ES5, the reduce() method can help reduce an array to a single value (by applying a function against an accumulator and each value of the array). To sum an array of integers using reduce(), you can do the following:

// ES5+
const integers = [-1, 2, 3, -4, 5];
const sum = integers.reduce(function (accumulator, value) {
    return accumulator + value;
}, 0);

console.log(sum); // output: 5

The same code can be written in a shorter syntax using the arrow function (introduced in ES6). For example:

// ES6+
const integers = [-1, 2, 3, -4, 5];
const sum = integers.reduce((accumulator, value) => accumulator + value, 0);

console.log(sum); // output: 5

Note that the 0 at the end is the initial value, and the accumulator holds the "reduced" value returned by the function in each iteration.

You may also use the Array.prototype.reduceRight() method. The difference between reduce() and reduceRight() is that the former goes through values left-to-right while the latter goes through values from right-to-left.

Using a Loop

You can simply use a loop to iterate over the entire array and sum the values. For example, to do that using a for loop, we can do the following:

const integers = [-1, 2, 3, -4, 5];
let sum = 0;

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

console.log(sum); // output: 5

You can also refactor the for loop in a shorter syntax like so:

const integers = [-1, 2, 3, -4, 5];
let sum = 0;

for (let i = 0; i < integers.length; sum += integers[i++]);

console.log(sum); // output: 5

Similarly, you may use other loops to sum all elements of an array of integers.


This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.