Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How could I write a for loop that adds up all the numbers in the array to a variable in JavaScript?
To sum all numbers in an array, initialize a total variable to 0, then iterate through the array and add each element to the total.
Let's say the following is our array with numbers:
var listOfValues = [10, 3, 4, 90, 34, 56, 23, 100, 200];
Using a for Loop
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);
Total Values = 520
Alternative Methods
You can also use other loop types or array methods:
var numbers = [10, 3, 4, 90, 34, 56, 23, 100, 200];
// Using for...of loop
let total1 = 0;
for (let num of numbers) {
total1 += num;
}
console.log("Using for...of:", total1);
// Using reduce() method
let total2 = numbers.reduce((sum, num) => sum + num, 0);
console.log("Using reduce():", total2);
Using for...of: 520 Using reduce(): 520
Comparison
| Method | Readability | Performance | Best For |
|---|---|---|---|
| for loop | Good | Fast | Learning basics |
| for...of | Better | Fast | Simple iteration |
| reduce() | Best | Moderate | Functional programming |
Conclusion
The traditional for loop provides full control and is perfect for learning. For cleaner code, consider using for...of or the reduce() method.
Advertisements
