Q:

How to Find the Sum of an Array of Numbers in JavaScript

0

How to Find the Sum of an Array of Numbers in JavaScript

All Answers

need an explanation for this answer? contact us directly to get an explanation for this 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:

<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.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

JavaScript / jQuery Frequently Asked Questions

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
How to Check If an Array Includes an Object in Jav... >>
<< How to Get the ID of the Element that Fired an Eve...