You've successfully subscribed to The Poor Coder | Hackerrank Solutions
Great! Next, complete checkout for full access to The Poor Coder | Hackerrank Solutions
Welcome back! You've successfully signed in.
Success! Your account is fully activated, you now have access to all content.
Finding the sum of an array of numbers in JavaScript

Finding the sum of an array of numbers in JavaScript

Beeze Aal
Beeze Aal

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?