How to use the for…of Loop In Javascript

The for…of loop provides a concise way to iterate over iterable objects such as arrays. This method checks each element to see if it is odd, and if so, adds it to a running total.

Example: In the provided JavaScript code, a function sumOfOddNumbers is defined to calculate the sum of odd numbers within an array using the for…of loop. The function iterates through the array, adding up the odd numbers encountered, and returns the total sum.

JavaScript
function sumOfOddNumbers(arr) {
    let sum = 0;
    for (const num of arr) {
        if (num % 2 !== 0) {
            sum += num;
        }
    }
    return sum;
}

const numbers = [1, 2, 3, 4, 5];
const oddSum = sumOfOddNumbers(numbers);
console.log("Sum of odd numbers:", oddSum);

Output
Sum of odd numbers: 9




JavaScript Program to Find Sum of Odd Numbers in an Array

In JavaScript, working with arrays is a common task. Often one needs to manipulate the elements within an array, such as finding specific values or calculating their sum.

Below are the approaches to find the sum of all odd numbers within an array:

Table of Content

  • 1. Using a loop
  • 2. Using the filter and reduce methods
  • 3. Using recursion
  • 4. Using forEach
  • 5. Using the for…of Loop

Similar Reads

1. Using a loop

This method loops over each element in the array, checking if it is odd or not. If so, the element is added to a running total variable, which holds the total of all odd numbers that have been visited up to this point....

2. Using the filter and reduce methods

This method provides a simpler answer by using built-in array features. By using the filter technique, a new array is created that only has the odd elements from the original array. The filtered array is then iterated by using the reduce method, which adds each element to the sum....

3. Using recursion

This method defines a recursive function that takes the array and the current index as arguments. It checks if the index is within the array bounds and if the current element is odd. If both conditions are met, the element is added to the sum and the function calls itself with the next index. The base case occurs when the index reaches the end of the array, returning the accumulated sum....

4. Using forEach

In this approach we use the forEach method to iterate over each element of the array. We use the condition num % 2 !== 0 to check if the number is odd. If the number is odd, we add it to the sum variable...

5. Using the for…of Loop

The for…of loop provides a concise way to iterate over iterable objects such as arrays. This method checks each element to see if it is odd, and if so, adds it to a running total....

Contact Us