LED Fantom
LED Fantom

Reputation: 1373

Accumulator returns NaN in reduce function in Javascript

I am learning to use ..., the spread operator, to write a function that takes all the parameters passed to a function and returns the sum of the even ones. My question is that why my acc equal to NaN except the first callback of reduce()?

The code and the executed print-out are below, and console.log(...) are the debugging code I inserted. Thank you for your help.

function sumEvenArgs(...args){
      var sum = args.reduce( (acc, next) => {
        console.log("\nnext:", next);
        if (next % 2 === 0) {
          acc += next;
          console.log("in if - acc:", acc);
        } else {
          acc += 0;
          console.log("in else - acc:", acc);
        }
      }, 0);

      return sum;
    }
    var sum = sumEven(1,2,3,4) // 6
    console.log("sum:", sum);

Output:

next: 1
in else - acc: 0

next: 2
in if - acc: NaN

next: 3
in else - acc: NaN

next: 4
in if - acc: NaN
sum: undefined

Upvotes: 0

Views: 982

Answers (1)

mostafa tourad
mostafa tourad

Reputation: 4388

you should return acc at the end of your callback function

function sumEvenArgs(...args){
    var sum = args.reduce( (acc, next) => {
        console.log("\nnext:", next);
        if (next % 2 === 0) {
            acc += next;
            console.log("in if - acc:", acc);
        } else {
            acc += 0;
            console.log("in else - acc:", acc);
        }
        return acc ; // you need to add this line 
    }, 0);

    return sum;
}
var sum = sumEvenArgs(1,2,3,4) // 6
console.log("sum:", sum);

Upvotes: 1

Related Questions