Finding the sum of an array of numbers in JavaScript

Finding the sum of an array of numbers in JavaScript

There are few different ways to find the sum of array of numbers in Javascript

Using for loop

The easiest and fastest option.

var array = [5, 7, 6 ,3 ,2];

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

console.log(sum); 

Using foreach loop

var array = [5, 7, 6 ,3 ,2];

var sum = 0;
array.forEach(i => sum+=i)
console.log(sum); 

Using map function

var array = [5, 7, 6 ,3 ,2];

var sum = 0;
array.map(i => sum+=i)
console.log(sum); 

Using reduce method

Syntax

array.reduce(function(total, currentValue, currentIndex, arr), initialValue)

Example

var array = [5, 7, 6 ,3 ,2];

var sum = array.reduce(function(a, b){
    return a + b;
}, 0);

console.log(sum); 

You can also use arrow function to make it look cleaner

var array = [5, 7, 6 ,3 ,2];

var sum = array.reduce((a,b) => a + b, 0);

console.log(sum); 

You can find here which method is the fastest for doing this job.

JS reduce vs map vs foreach vs for loop
Which is the fastest method among reduce vs map vs foreach vs for loop?

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe