ajaykumar
ajaykumar

Reputation: 656

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.

Upvotes: 1

Views: 1369

Answers (1)

robertklep
robertklep

Reputation: 203251

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)

Upvotes: 5

Related Questions