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.

JavaScript
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

Similar Reads

Using a For Loop

The traditional for loop is one of the most direct way to iterate over an array and sum its elements. You initialize a sum variable to zero, then iterate through each element of the array, adding each element to the sum....

Using a While Loop

A while loop can also be used to sum the elements of an array. This method involves initializing a counter and a sum variable, then using the while loop to iterate through the array elements until the counter reaches the array’s length....

Using Array.prototype.reduce() method

The reduce() method provides a functional programming approach to summing array elements. This method takes a reducer function that accumulates the sum of the array elements and an initial value for the accumulator....

Using For-Of Loop

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....