'Javascript. Reduce an array by adding only odd numbers. Javascript returns NaN when I use %2 on a number with if [duplicate]

I am trying to sum all odd numbers of an array. The following method does not work and returns NaN. Could someone explain me why? I found a workaround so I do not need an alternative code. It would be great if you could explain me why (a supposed number)%2 is NaN. Thanks a lot. (I have just started learning Javascript. So sorry if this is ... )

let arr=[1,2,3,4,5,6,7]

let result = arr.reduce((accumulator, currentValue) => {
  if (currentValue%2 >0){
    return accumulator + currentValue}})
console.log(result)


Solution 1:[1]

You are not returning the accumulator if the it's an odd number, so the last result is undefined + 7 which is NaN.

Always return the current accumulator for even numbers, or the accumulator + the number if it's an odd number.

const arr=[1,2,3,4,5,6,7]

const result = arr.reduce((accumulator, currentValue) =>
  currentValue % 2 > 0 ? accumulator + currentValue : accumulator
)

console.log(result)

Solution 2:[2]

You return undefined for all even values (this is standard for all functions without a return statement) and undefined can not be used to add a number.

For preventing this, you need to return the accumulator.

let arr = [1, 2, 3, 4, 5, 6, 7],
    result = arr.reduce((accumulator, currentValue) => {
        if (currentValue % 2 > 0) {
            return accumulator + currentValue;
        } // or use else here
        return accumulator;
    });

console.log(result);

Solution 3:[3]

You just need to add an else clause inside the reduce method.

Because for even numbers you don't return anything which means the function returns undefined and now when the code encounters an odd number it does undefined + something which is NaN.

let arr = [1, 2, 3, 4, 5, 6, 7];

let result = arr.reduce((accumulator, currentValue) => {
  if (currentValue % 2 > 0) {
    return accumulator + currentValue;
  } else {
    return accumulator
  }
});

console.log(result);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Ori Drori
Solution 2
Solution 3