Finding the sum of an array of numbers in JavaScript
- Published
- Updated
- Reading time
- 1 min read
- Length
- 193 words
On this page
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.