Web Tools Table Maker3schools TranslateImage CompressorFavicon Icon GeneratorCrop & Resize Image
Apu
Apu March 29, 2023 › #Array #for-loop

How to sum values in array using for loop in JavaScript

Are you looking for ways to sum values in an array using JavaScript? Look no further! In this article, I'll discuss three different methods of how to sum values in an array using a for loop.

Using the traditional for loop. #

The first method is the traditional "for loop". This involves setting up a variable that will store our total as we iterate through each element of the array and add it to our running total.

For example:

<script>
 let numbers = [1, 2, 3, 4, 5];
 let total = 0;   
  for(i=0; i<numbers.length; i++){
     total += numbers[i];       
  }
  console.log(total); // output 15       
</script>

Using forEach() method. #

The second way is by utilizing the forEach() method which allows us to execute a function on every item within an array without having explicitly write out code for each one individually like before.

<script>
 let numbers = [1, 2, 3, 4, 5];
 let total = 0;   
  numbers.forEach(function(num) {       
    total += num ;             
  }); 
  console.log(total); // output 15       
</script>

Using for...of #

Lastly there's also "For...of" syntax which lets us iterate over any type of data such as strings or objects not just arrays :
<script>
 let numbers = [1, 2, 3, 4, 5];
 let total = 0;   
  for(let e of numbers){       
    total += e ;             
  } 
  console.log(total); // output 15       
</script>
save
listen
AI Answer
Write Your Answer
loading
back
View All