ajaykumar ajaykumar - 3 months ago 10
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

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)