Finding the sum of an array of numbers in JavaScript
1 min read

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?

Enjoying these posts? Subscribe for more


Adblocker detected! Please consider reading this notice.

We've detected that you are using AdBlock Plus or some other adblocking software which is preventing the page from fully loading.

That's okay. But without advertising-income, we can't keep making this site awesome.

We don't have any banner, Flash, animation, obnoxious sound, or popup ad. We do not implement these annoying types of ads!

We need money to operate the site, and almost all of it comes from our online advertising.

Please add thepoorcoder.com to your ad blocking whitelist or disable your adblocking software.

×