1

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.

6
  • checkout the syntax of array reduce arr.reduce(callback[, initialValue]) where initial value is used as the first argument to the first call of the callback. Commented Aug 30, 2016 at 6:01
  • I have seen that . In first case it ignores the initial undefined however in second case it returns NaN. Let me add one more example for better clarity Commented Aug 30, 2016 at 6:03
  • it's because you are trying to add undefined with a number try [1,2].reduce(function(initial , val){ initial = initial?initial:0 return initial+val; }, undefined) Commented Aug 30, 2016 at 6:07
  • Your example is working but the confusion what is the actual difference between the second and third case as in both the cases initial has undefined. Commented Aug 30, 2016 at 6:13
  • it's an optional parameter right ?? Commented Aug 30, 2016 at 6:16

1 Answer 1

5

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.