How could I write a for loop that adds up all the numbers in the array to a variable in JavaScript?

JavascriptWeb DevelopmentObject Oriented Programming

At first, declare and initialize the total variable with 0 and then you need to iterate over all the array and extract all the values of array and add up with the updated total variable.

Let’s say the following is our array with numbers −

var listOfValues = [10,3,4,90,34,56,23,100,200];

Example

var listOfValues = [10,3,4,90,34,56,23,100,200];
var total = 0;
for(let index = 0; index < listOfValues.length ; index++){
   total=total+listOfValues[index];
}
console.log("Total Values="+total);

To run the above program, you need to use the following command −

node fileName.js.

Here, my file name is demo86.js.

Output

This will produce the following output −

PS C:\Users\Amit\JavaScript-code> node demo86.js
Total Values=520
raja
Published on 07-Sep-2020 08:13:46

Advertisements