Sum Of An Array In JavaScript

In this tutorial we learn 2 type of Sum Of An Array In JavaScript

1. Use the for Loop to Sum an Array in a JavaScript

2. Use the reduce() Method to Sum an Array in a JavaScript

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

Ex. 1 - Use the for Loop to Sum an Array in a JavaScript

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

<script>
const array = [1, 2, 3, 4, 5];
let sum = 0;
for (let i = 0; i < array.length; i++) {
    sum += array[i];
}
console.log(sum);
</script>

Ex. - 2. Use the reduce() Method to Sum an Array in a JavaScript

In this tutorial You can use the reduce() method in javascript to find or calculate the sum of an array of numbers.

The reduce() method in javascript executes the specified reducer function on each member of the array resulting in a single output value, see example:

   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);