sum all odd numbers in javascript

index.tsx
function sumOddNumbers(numbers) {
  let sum = 0;
  for (let i = 0; i < numbers.length; i++) {
    if (numbers[i] % 2 !== 0) {
      sum += numbers[i];
    }
  }
  return sum;
}

const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9];
console.log(sumOddNumbers(numbers)); // Output: 25
274 chars
13 lines

In this code snippet, we define a function called sumOddNumbers that takes an array of numbers as its parameter. We declare a variable called sum with an initial value of 0. We then loop through each element in the numbers array using a for loop and check if each number is odd. If so, we add it to the sum variable.

Finally, we return the sum variable, which will be the sum of all odd numbers in the numbers array. We test the sumOddNumbers function with an example array [1, 2, 3, 4, 5, 6, 7, 8, 9] and output the result to the console, which will output 25.

gistlibby LogSnag