Skip to content
Advertisement

how does initialValue work in javascript reduce function?

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.

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement