Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

How to find the sum of all elements of a given array in JavaScript ?

  • Difficulty Level : Hard
  • Last Updated : 08 Oct, 2021

In this article, we will learn how we can find the sum of all elements/numbers of the given array. There are many approaches to solve the problems that are described below through examples.

Example 1: In this example, we are simply going to iterate over all the elements of the array using a for loop to find the sum.

Filename: gfg.js

Javascript




<script>
    // Creating array
    var arr = [4, 8, 7, 13, 12]
  
    // Creating variable to store the sum
    var sum = 0;
  
    // Running the for loop
    for (let i = 0; i < arr.length; i++) {
        sum += arr[i];
    }
  
    document.write("Sum is " + sum) // Prints: 44
</script>


Output:

Sum is 44

Example 2: In this example, we are going to use forEach method of the array to calculate the sum.

Filename: gfg.js

Javascript




<script>
      
    // Creating array
    var arr = [4, 8, 7, 13, 12]
  
    // Creating variable to store the sum
    var sum = 0;
  
    // Calculation the sum using forEach
    arr.forEach(x => {
        sum += x;
    });
  
    // Prints: 44
    document.write("Sum is " + sum);
</script>


Output:

Sum is 44

Example 3: In this example, we are going to use reduce() method to find the sum of the array.

Filename: gfg.js

Javascript




<script>
  
    // Creating array
    var arr = [4, 8, 7, 13, 12]
  
    // Using reduce function to find the sum
    var sum = arr.reduce(function (x, y) {
        return x + y;
    }, 0);
  
    // Prints: 44
    document.write("Sum using Reduce method: " + sum);
  
</script>


Output:

Sum using Reduce method: 44


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!