How to use a loop In Javascript
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.
Example: In the provided JavaScript code, a function sumOfOddNumbers is defined to calculate the sum of odd numbers within an array. This function iterates through the array, adding up the odd numbers encountered, and returns the total sum.
function sumOfOddNumbers(arr) {
let sum = 0;
for (let i = 0; i < arr.length; i++) {
if (arr[i] % 2 !== 0) {
sum += arr[i];
}
}
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