Web Tools Table Maker3schools TranslateImage CompressorFavicon Icon GeneratorCrop & Resize Image
Apu
Apu April 01, 2023 › #Array #HowTo

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

If you're looking for a way to find the sum of all elements in an array using JavaScript, then look no further! Today I'll be discussing two different methods that can help you get the job done: the forEach() method and reduce() method.

JavaScript Program to Find the Sum of Array Using forEach Method #

The first option is to use a loop such as a forEach() loop. This will allow us to iterate over each element in our array and add them together until we have reached our desired result. To do this, simply create your loop like so:

<script>
  let total = 0; 
  let myArr = [5, 6, 7]
   myArr.forEach(function (num) {   
       total += num; 
   });     
   console.log(total);
</script>
Prints out final value of 'total' after entire iteration has been completed. Output : 18

With this approach, we are able to go through every single item within our given array and add them up one by one until there's nothing left!

JavaScript Program to Find the Sum of Array Using reduce() Method #

The second option would be utilizing something called reduce(). The reduce() method adds the elements of the array one by one, starting from the initial value, and returns the final sum of all the elements.

<script>
  const array = [5, 6, 7];
  const sum = array.reduce((accumulator, currentValue) => accumulator + currentValue, 0);
  console.log(sum);
</script>

Here, reduce() method is called with two arguments: an arrow function that calculates the sum of the two values passed to it as parameters, and an initial value set to 0.

save
listen
AI Answer
Write Your Answer
loading
back
View All