Reduce method javascript

Reduce method javascript

function sumFibs(num) {
  var arr=[1,1];
  var sum=0;
  var i=0;
// array created [1,1,2,3,5,8] at this point
//now to add oddnumbers and return result
 return arr.reduce(function(total,value){
     if(value%2){//if value is odd only then add result
       console.log(value);//here at 'value' is 1,3,5 respective iteration.
        console.log(total+value);//here total is 2, NaN,NaN
       return total+value;

console.log(sumFibs(10));//here it return undefined

Now my question is why it is showing NaN at 2nd and 3rd iteration of reduce method. It will check if number is odd so it will take that odd number add it in total and return it to total and then next value will come. Isn’t it working like that. I am actually new and weak in these JS built-in methods. The program is to add all odd fabinocci numbers. Required result is 10 of upper program


You are only returning total if it the value is odd. You still need to return total when value is even, but you just do not need to add the value to it. If not, reduce will use undefined for total which will end up being NaN.