How to use forEach In Javascript
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
Example: Below example uses forEach method to calculate the sum of odd numbers.
const array = [1, 2, 3, 4, 5];
let sum = 0;
array.forEach((num) => {
if (num % 2 !== 0) {
sum += num;
}
});
console.log("Sum of all numbers: ",sum);
Output
Sum of all 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