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:
<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.
Use the JavaScript
reduce()
MethodYou 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: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.
need an explanation for this answer? contact us directly to get an explanation for this answer