-1

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)
  • 2
    If the `if` test is `false` the function will return `undefined`. – Pointy Apr 07 '21 at 15:42
  • 1
    The callback of `.reduce()` _always_ has to return the value for `accumulator` of the next round: _"Your reducer function's returned value is assigned to the accumulator, whose value is remembered across each iteration throughout the array, and ultimately becomes the final, single resulting value."_ – Andreas Apr 07 '21 at 15:44

3 Answers3

0

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)
Ori Drori
  • 145,770
  • 24
  • 170
  • 162
0

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);
Som Shekhar Mukherjee
  • 3,348
  • 1
  • 3
  • 19
0

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);
Nina Scholz
  • 323,592
  • 20
  • 270
  • 324