Javascript Reduce an empty array

agusgambina picture agusgambina · Apr 29, 2014 · Viewed 59.1k times · Source

When I reduce the array, I am trying to get the number zero, but I dont clearly understand the behaviour of the function

[].reduce(function(previousValue, currentValue){
  return Number(previousValue) + Number(currentValue);
});

result

TypeError: Reduce of empty array with no initial value

seems that if the array is empty I can't reduce it

[""].reduce(function(previousValue, currentValue){
  return Number(previousValue) + Number(currentValue);
});

result

""

If the only element in the array is an empty string, retrieves an empty string

Answer

xdazz picture xdazz · Apr 29, 2014

The second parameter is for initial value.

[].reduce(function(previousValue, currentValue){
  return Number(previousValue) + Number(currentValue);
}, 0);

or using ES6:

[].reduce( (previousValue, currentValue) => previousValue + currentValue, 0);