Top ways to sum for an array of numbers in javascript(example)

This tutorial shows multiple ways to sum for an array of numbers in javascript with an example using foreach, for index, for of syntax and array reduce function.

let’s first declare an array as input

var myarray = [7, 8, 1, 9];

Output after adding all the numbers in the array.

7+8+1+9=25

You can check related posts before you start learning.

Sum of an array of numbers in javascript

  • use for loop to iterate an array using index loop

For loop is a basic loop in JavaScript to iterate an array. index in for loop is used to access array elements. Iterates an array using an index starting from zero until the length of the array is reached.

temporary variable is used to store each iterate array value. add iterated value to a variable, which is used to store the final result.

Here is an example code

var myarray = [7, 8, 1, 9];
var result = 0;
for (var i = 0; i < myarray.length; i++) {
  result += myarray[i];
}
console.log(result); //25
  • use ES6 for-of loop ES6 provides for of loop to iterate an array of elements in another way.

It iterates an element in an array using an index. array[index] returns the element for a given index.

Syntax:

for(index of array){
    get element using array[i] syntax
}

Here is an example

var myarray = [7, 8, 1, 9];
var sum = 0;
for (var k in myarray) {
  sum += myarray[k];
}
console.log(sum);

Output:

25
  • use a forEach loop

Another way is to use the forEach loop to iterate an array.

The forEach loop accepts a callback function with each element. The callback can be a normal function or an arrow function in ES6.

Here is an example.

let result = 0;
myarra.forEach((item) => {
  result += item;
});
console.log(result); // 25
  • use the lodash sum function

if you are using lodash in your project, you can use the sum function in the array object. It calculates the sum of numbers in an array and returns the result.

Here is a lodash sum function example.

var myarray = [7, 8, 1, 9];
result = _.sum(myarray);
console.log(result); // 25
  • use array reduce function

Array reduce is a reduced function and reduces the array elements.

It accepts a callback function The function is normal function ES6 arrow function or lambda expressions

Here is an example code

var myarray = [7, 8, 1, 9];

const sum = (first, second) => first + second;
const result = myarray.reduce(sum);
console.log(result); // 25

Conclusion

To summarize, this tutorial shows multiple ways to the addition of numbers to an array.