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 solving the problems using for loop, forEach() method, and reduce() method.
Below all the approaches are described with a proper example:
- Using for loop
- Using forEach() Method
- Using forEach() Method
- Using Recursion
Method 1: Using for loop
We are simply going to iterate over all the elements of the array using a Javascript for loop to find the sum.
Example: This example shows the above-explained approach.
Javascript
// Creating arraylet arr = [4, 8, 7, 13, 12]Â
// Creating variable to store the sumlet sum = 0;Â
// Running the for loopfor (let i = 0; i < arr.length; i++) {Â Â Â Â sum += arr[i];}Â
console.log("Sum is " + sum) // Prints: 44 |
Sum is 44
Method 2: Using forEach() Method
We are going to use the Javascript forEach() method of the array to calculate the sum.
Example: This example shows the above-explained approach.
Javascript
// Creating arraylet arr = [4, 8, 7, 13, 12]Â
// Creating variable to store the sumlet sum = 0;Â
// Calculation the sum using forEacharr.forEach(x => {Â Â Â Â sum += x;});Â
// Prints: 44console.log("Sum is " + sum); |
Sum is 44
Method 3: Using reduce() Method
We are going to use the Javascript reduce() method to find the sum of the array.
Example: This example shows the above-explained approach.
Javascript
// Creating arraylet arr = [4, 8, 7, 13, 12]Â
// Using reduce function to find the sumlet sum = arr.reduce(function (x, y) {Â Â Â Â return x + y;}, 0);Â
// Prints: 44console.log("Sum using Reduce method: " + sum); |
Sum using Reduce method: 44
Method 4: Using Recursion
We could define recursion formally in simple words, that is, a function calling itself again and again until it doesn’t have left with it anymore.
Example: This example shows the above-explained approach.
Javascript
// Creating arraylet arr = [4, 8, 7, 13, 12];Â
// Function to find the sum of the array using recursionfunction sumArray(arr, index) {Â Â Â Â if (index === arr.length) {Â Â Â Â Â Â Â Â return 0;Â Â Â Â }Â Â Â Â return arr[index] + sumArray(arr, index + 1);}Â
console.log("Sum is " + sumArray(arr, 0)); |
Sum is 44
