I'm sure I'm reading this wrong but MDN says this...
initialValue
Value to use as the first argument to the first call of the callback. If no initial value is supplied, the first element in the array will be used. Calling reduce() on an empty array without an initial value is an error.
then says this...Aren't these saying different things? Thanks!
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.
The wording is a bit confusing, I agree.
Putting the two statements together:
If no initial value is supplied, the first element in the array will be used
If initialValue isn't provided, reduce() will execute the callback function starting at index 1, skipping the first index
These two statements are actually describing two different characteristics of the reduce operation when no initial value is provided:
Does this wording make more sense?:
If no initial value is provided, the first element will be used as the initial value. In this case, the callback function will start at index 1, since index 0 has already been accounted for by using it's value as the default starting value.
Unfortunately, I can't just add a comment. Try this, please. This is another explanation of .reduce() function with an example how it works on http://javascript.info. Probably, it will help you to understand this better.
Also, here is the answer to your question about an exception on an empty array without the initial value in another StackOverflow's discussion.
If no initialValue was provided, then previousValue will be equal to the first value in the array and currentValue will be equal to the second. It is a TypeError if the array contains no elements and initialValue is not provided.
Update: probably, this article How JavaScript’s Reduce method works, when to use it, and some of the cool things it can do on freeCodeCamp will be useful.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With