Netside
Netside

Reputation: 80

Why is an empty array being passed as a parameter to .reduce?

I was reading the developer docs here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce

I just wonder why there is an empty array being passed where you would normally indicate the initialvalue?

Image/Code Snippet from MSDN

Upvotes: 0

Views: 209

Answers (2)

CertainPerformance
CertainPerformance

Reputation: 370689

The only benefit I can see would be if the array you're trying to flatten is empty. In that case, if an initial value is not passed, the .reduce will throw an error, because there's nothing to iterate over and no initial value to immediately return.

When the array being reduced has no items, the initial value is returned. If there's no initial value, the below error is thrown.

const makeFlat = arr => arr.reduce(
  ( accumulator, currentValue ) => accumulator.concat(currentValue)
);

console.log(makeFlat([['foo']])); // OK

console.log(makeFlat([])); // Error

Uncaught TypeError: Reduce of empty array with no initial value

So, to make the implementation as generic as possible, to work even when one tries to flatten an empty array, pass an initial value of [].

Upvotes: 1

khavinshankar
khavinshankar

Reputation: 11

the above code calls concat() on accumulator, concat() only works on arrays and strings, so it is initialized as an empty array.

To know more about concat()

Upvotes: 0

Related Questions