Having a hard time understanding rest argument

I’m having a hard time understanding the solution of Use the Rest Parameter with Function Parameters in ES6

const sum = (...args) => {
  return args.reduce((a, b) => a + b, 0);
}

console.log(sum(0,1,2))

especially this line: args.reduce((a,b) => a+b, 0);
what does it do exactly? what happen on this line?

In this example we’re using ... rest operator to get an array of all the arguments that will be passed to sum function.

const sum = (...args) => {
  console.log(args);
}
sum(0, 1, 2);
// [0, 1, 2];

Once we have an array, we can use reduce method which is available for all arrays.

Array.prototype.reduce()

1 Like

According to MDN, " The rest parameter syntax allows a function to accept an indefinite number of arguments as an array". Basically, if you don’t know how many arguments will be passed to your function you can use rest parameter syntax and it will put all the arguments in an array for you.

The reduce method can do a few different things, but in this case it’s just adding up all the numbers in the array to get the total.

Check out the example here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/rest_parameters

You can also play around with the values you enter and see what results you get.

1 Like

oh my god, I thought “(a, b)” means, the function only accept two value from …args, but now that I read the article you provided. It actually applied the function to each values inside the array. thanks you so much!

But I still have a question, if you don’t mind.
do you know what that 0 is, at the end return args.reduce((a, b) => a + b, 0);

The 0 is the ‘initial value’. In this case it doesn’t do anything because essentially it just means ‘add up all the values starting from 0’, which is what the default is anyway. You can remove it and the function will still work the same. It’s optional to have it.

However try changing it to 5 or 10 and you will get different results. If you change it to 5, then you are saying ‘add up all the values starting from 5’.

Check out the link to the reduce method that @sitek94 posted. They have a nice example of that in the demo on line 9.

Hope that helps!

1 Like