Reputation: 656
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.
Upvotes: 1
Views: 1369
Reputation: 203251
Explaination here:
Note: If
initialValue
isn't provided, reduce will execute the callback function starting at index 1, skipping the first index. IfinitialValue
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)
Upvotes: 5