Confusion with the function syntax?

Tell us what’s happening:

Your code so far

const sum = (x, y, z) => {
  const args = [x, y, z];
  return args.reduce((a, b) => a + b, 0);

i have already resolved the challenge but just for checking purpose i tried to re-write the above code in this format.

const sum = (...args) => {
  console.log(args.reduce(function (a, b)
    return  a + b, 0

sum(1,2,3,4) // output is 0
sum() // output is TypeError: Reduce of empty array with no initial value
sum(5) // output is 5

what am i missing here? what does that comma after a+b shows, i am just trying to rewrite the function syntax.
please suggest.

Your browser information:

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

Challenge: Use the Rest Parameter with Function Parameters

Link to the challenge:

You’re initializing the value of the accumulator in reduce() method wrong. I don’t know if you’ve studied about the method yet but the later challenges cover that for you so if you haven’t and don’t plan to for now, just don’t change the syntax and try using the provided arrow function. You place that 0 after the function, go ahead and do your studying if you’re into it. And the correct code in your syntax in as follows—

const sum = (...args) => {
  return args.reduce(function (a, b) {
    return a + b;
  }, 0);                                 // As you can see, the 0 is after the function finishes, it's a separate parameter of the reduce() method

To phrase that a slightly different way, .reduce() takes two arguments. The first one is a function and the second one is the initial value of the accumulator. 0 is the second argument, not part of the return value of the function.

1 Like