1

Version 1:

var c = [ '##' ]

console.log(c.reduce(function(a,b){
 return  b.length
}, 0)) // 2

Version 2:

var c = [ '##' ]

console.log(c.reduce(function(a,b){
 return  b.length
})) // "##"

I'm just curious as to why length method doesn't work if I don't provide the initial value as you can see in the version 2?

So can someone tell me in this case why do I need to provide the initial value for length method to work?

0

1 Answer 1

4

Version 1

From MDN Docs for Array#reduce

The first time the callback is called, previousValue and currentValue can be one of two values. If initialValue is provided in the call to reduce, then previousValue will be equal to initialValue and currentValue will be equal to the first value in the array.

In version #1, the initialValue is provided. So, According to the Docs, previousValue is assigned as the initialValue

So, for the first iteration:

previousValue = initialValue
previousValue = 0

And nextValue is the first element in the array.

nextValue = '##'

So, the returned value 2.


Version 2self-explanatory

If the array is empty and no initialValue was provided, TypeError would be thrown. If the array has only one element (regardless of position) and no initialValue was provided, or if initialValue is provided but the array is empty, the solo value would be returned without calling callback.

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.