How to use for loop In Javascript
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.
// Creating array
let arr = [4, 8, 7, 13, 12]
// Creating variable to store the sum
let sum = 0;
// Running the for loop
for (let i = 0; i < arr.length; i++) {
sum += arr[i];
}
console.log("Sum is " + sum) // Prints: 44
Output
Sum is 44
How to find the sum of all elements of a given array in JavaScript ?
Finding the sum of all elements in a given array in JavaScript involves iterating through the array and accumulating the values using a loop or array method like reduce(). This process yields the total sum of all array elements.
Below all the approaches are described with a proper example:
Table of Content
- Using for loop
- Using forEach() Method
- Using reduce() Method
- Using Recursion
- Using Lodash _.sum() Method
Contact Us