How to Find the Sum of an Array of Numbers in JavaScript
Topic: JavaScript / jQueryPrev|Next
Answer: Use the JavaScript reduce()
Method
You can use the reduce()
method to find or calculate the sum of an array of numbers.
The reduce()
method executes the specified reducer function on each member of the array resulting in a single output value, as demonstrated in the following example:
Example
Try this code »<script>
var array = [1, 2, 3, 4, 5];
// Getting sum of numbers
var sum = array.reduce(function(a, b){
return a + b;
}, 0);
console.log(sum); // Prints: 15
</script>
The 0
in the example above (line no-7) is the initialValue i.e. the value to use as the first argument to the first call of the callback. If no initial value is supplied, the first element in the array will be used.
If the array is empty and no initialValue is provided, an error will be thrown. So it is safer to provide an initial value such as 0 if you're performing addition, and 1 if you're performing multiplication.
Related FAQ
Here are some more FAQ related to this topic: