agusgambina agusgambina - 3 months ago 8
Javascript Question

Javascript Reduce an empty array

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

Thank you

Answer

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);