How to use For-Of Loop In Javascript
For-of loop is a modern and concise way to iterate over array elements. This loop directly iterates through the values of the array, making it easy to sum the elements.
Example: To demonstrate the sum of all elements in an array using a for-of loop and prints the result.
let array = [1, 2, 3, 4, 5];
let sum = 0;
for (let value of array) {
sum += value;
}
console.log(sum);
Output
15
How to Add the Numbers in a JavaScript Array?
Adding the numbers in a JavaScript array is a common operation, particularly in tasks involving data aggregation or mathematical calculations. This process involves iterating through the array and summing its elements. JavaScript provides multiple methods to achieve this, ranging from traditional loops to more modern and concise array methods.
Table of Content
- Using a For Loop
- Using a While Loop
- Using Array.prototype.reduce()
- Using For-Of Loop