Reputation: 80
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?
Upvotes: 0
Views: 209
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
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