Rest Parameter in Functions

I was working through the Rest Parameter with Function Parameters challenge and for the most part, I understood it except for when the function was called with an empty array.

My initial answer to the problem was as follows:


const sum = (...args) => {
  const reducer = (previousValue, currentValue) => previousValue + currentValue;
  return args.reduce(reducer);
}

However when the code was called with the following


consol.log(sum());

It was not returning sum to be 0 as expected. To correct the issue I had to do the following:


const sum = (...args) => {
  const reducer = (previousValue, currentValue) => previousValue + currentValue;
  return args.reduce(reducer,0);
}

// added a 0 after the call to the reducer const variable

To return 0 if the function got called with an empty array do you have to add a default value? Is that what I did with adding the 0 after the call to the reducer variable? Not sure I fully understand why adding the 0 solved the problem.

Thanks in advance for the help!!

  **Your browser information:**

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.81 Safari/537.36

Challenge: Use the Rest Parameter with Function Parameters

Link to the challenge:

From MDN:

“If initialValue is not specified, previousValue is initialized to the first value in the array, and currentValue is initialized to the second value in the array.”

So in this particular case, if you don’t pass a numerical value into sum() then reduce can’t determine the previousValue and thus it won’t work. In fact, reduce throws a TypeError when this happens (the FCC tests are just hiding that from you, but if you add your own try/catch block you can see it). And that is also explained in the MDN docs:

"Exceptions

Throws a TypeError if the array contains no elements and initialValue is not provided."

Hence, providing the initial value 0 to reduce prevents the error when no number is passed into sum.

@bbsmooth , Yea after I posted this I did try on my own device and noticed the TypeError. Thanks for helping clear that up!!