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.

javascript
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

javascript
var array = [5, 7, 6 ,3 ,2]; var sum = 0; array.forEach(i => sum+=i) console.log(sum);

Using map function

javascript
var array = [5, 7, 6 ,3 ,2]; var sum = 0; array.map(i => sum+=i) console.log(sum);

Using reduce method

Syntax

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

Example

javascript
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

javascript
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.
jamie@example.com
Subscribe