Quick question on Reduce

Tell us what’s happening:
In this simple function, I am just wondering what the 0 after a+b is referring to. I searched up some documentation on reduce() and none of the other examples seem to have two arguments after =>.

  **Your code so far**

const sum = (...args) => {
return args.reduce((a, b) => a + b, 0);
  **Your browser information:**

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 11_2_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.114 Safari/537.36.

Challenge: Use the Rest Parameter with Function Parameters

Link to the challenge:

Reduce takes two arguments: the callback function and the initial value the reduce operation should start with (in this case, 0).

args.reduce((a, b) => a + b, 0)

The function (a, b) => a + b is one argument, and 0 is the second argument

1 Like

Hi @ligaoge

The 0 has nothing to do with the arrow function. It is the second argument to reduce. This is how MDN describes it.

A value to use as the first argument to the first call of the callback . If no initialValue is supplied, the first element in the array will be used as the initial accumulator value and skipped as currentValue . Calling reduce() on an empty array without an initialValue will throw a TypeError .


1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.