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