ajaykumar ajaykumar - 1 year ago 50
Javascript Question

Explicit passing initial value as undefined in array reduce


I was testing few scenarios with array reduce function.


[1,2].reduce(function(initial , val){

return initial+val;
} ,1)
// returns 4 as expected


[1,2].reduce(function(initial , val){

return initial+val;
})
// returns 3



But explicitly passing undefined as initial value


[1,2].reduce(function(initial , val){

return initial+val;
}, undefined)
// returns NaN.



It appears unusual to me


.

Answer Source

Explaination here:

Note: If initialValue isn't provided, reduce will execute the callback function starting at index 1, skipping the first index. If initialValue is provided, it will start at index 0.

So your second case is similar to this:

[2].reduce(function(initial, val){
    return initial+val;
}, 1)