Paul N
Paul N

Reputation: 613

How does reduce decide its initial value, when it's not provided?

How does javascript's reduce function determine its initial value, when it is not passed? Does it simply default to the number 0?

Why do these two work:

[1, 2, 3, 4].reduce((sum, currentValue) => {
  return sum + currentValue;
});

[1, 2, 3, 4].reduce((string, currentValue) => {
  return `${string}` + currentValue;
});

But this doesn't?

[1, 2, 3, 4].reduce((object, currentValue) => {
  object[currentValue] = currentValue;
  return object;
});

Upvotes: 0

Views: 2698

Answers (1)

Mamun
Mamun

Reputation: 68933

Array.prototype.reduce() initialValue (Optional)

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.

Upvotes: 4

Related Questions