Sum of an Array in JavaScript

  1. Use the for Loop to Add Numbers in a JavaScript Array
  2. Use the reduce() Method to Add Numbers in a JavaScript Array
  3. Use the lodash Library to Add Numbers in a JavaScript Array

This tutorial teaches how to get the sum of an array of numbers in JavaScript.

Use the for Loop to Add Numbers in a JavaScript Array

The for loop is used to iterate an array. We can use it to add all the numbers in an array and store it in a variable.

const array = [1, 2, 3, 4];
let sum = 0;

for (let i = 0; i < array.length; i++) {
    sum += array[i];
}
console.log(sum);

We initialize a variable sum as 0 to store the result and use the for loop to visit each element and add them to the sum of the array.

Use the reduce() Method to Add Numbers in a JavaScript Array

The reduce() method loops over the array and calls the reducer function to store the value of array computation by the function in an accumulator. An accumulator is a variable remembered throughout all iterations to store the accumulated results of looping through an array. We can use this to iterate through the array, add the element’s value to the accumulator and get the sum of the array.

const arr = [1, 2, 3, 4];
const reducer = (accumulator, curr) => accumulator + curr;
console.log(arr.reduce(reducer));

Use the lodash Library to Add Numbers in a JavaScript Array

The lodash library has a sum method that can easily add the numbers present in an array.

var lodash = require('lodash');
var arr = [3, 6, 1, 5, 8];
var sum = lodash.sum(arr);
console.log(sum); 

All the methods discussed above are compatible with all the major browsers.

Contribute
DelftStack is a collective effort contributed by software geeks like you. If you like the article and would like to contribute to DelftStack by writing paid articles, you can check the write for us page.

Related Article - JavaScript Array

  • Randomize or Shuffle an Array in JavaScript
  • Compare Two Arrays in JavaScript