How to get the sum of an array elements in JavaScript?

To get the sum of an array elements in JavaScript, you can use the array.reduce(callback, initialValue) method. The reduce() method allows you to call the callback function once for each array element in ascending index order (left to right). The reduce() method returns a single value: the result of the last callback function call. The range of elements processed by the reduce() method is set before the first call to the callback function. If elements were added to the array after it was called, then the function will not be called on such elements. If the array has only one element (regardless of position) and no initialValue is specified, or if initialValue is provided, but the array is empty, then the value of that element will be returned without calling the callback. You can also find the sum of an array in JavaScript with a "for" loop. In this JavaScript Array Sum Example, we use the reduce() method to get the sum of the array elements. Below you can see more examples of calculating the sum of a JavaScript array with detailed descriptions. Click Execute to run the JavaScript Array Sum Example online and see the result.
How to get the sum of an array elements in JavaScript? Execute
let array =  [1, 2, 3, 4, 5];

let result = array.reduce((a, b) => {
  return a + b;
});

console.log(result)
Updated: Viewed: 1087 times

How to find the sum of array elements in JavaScript?

To find the sum of array elements in JavaScript, you need to use the array.reduce(function(total, currentValue, currentIndex, array), initialValue) method. The callback function given as a parameter to the reduce() method will not be called on removed or missing array elements. The array.reduce() method does not change the array it was called on. The range of elements processed by the reduce() method is set before the first call to the callback function. If elements were added to the array after it was called, then the function will not be called on such elements.

The callback function's return value is provided as an argument the next time the function is called, causing the return value of the last call to become the return value of the method (the value is computed from the elements of the array).

JavaScript Array Sum Example
let array = [1, 2, 3, 4, 5];

let sum = array.reduce(function(a, b){
  return a + b;
});

console.log(sum);

// output: 15

How to sum an array using a for loop in JavaScript?

The for loop is used to iterate over an iterable object. We can use a for loop to iterate through the array elements and sum their values.

JavaScript Array Sum with for loop Example
let array = [10, 20, 30, 40, 50];
let sum = 0;

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

console.log(sum);

// output: 150

See also