Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how does initialValue work in javascript reduce function?

Tags:

javascript

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.

like image 878
JMay Avatar asked Jan 17 '18 01:01

JMay


2 Answers

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:

  1. The default value used as the initial value
  2. The starting array index that the operation will use

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.

like image 97
Jonathan.Brink Avatar answered Oct 22 '22 21:10

Jonathan.Brink


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.

like image 25
Alexandr Avatar answered Oct 22 '22 22:10

Alexandr