Rest parameter! how does it work?

Hello everyone! I am taking this lesson: ES6: Use the Rest Parameter with Function Parameters, and I don’t get the way Rest Parameter works, so I have two questions. Please.

For example, let’s suppose this is my code:
const sum = (…args) => {
return args.reduce((a, b) => a + b, 0);
console.log(sum(1, 2, 3)); // 6

My first question: As it doesn’t set any fixed arguments, unlike the rest parameter, so I don’t know exactly how many arguments I am going to have, later on, “return args.reduce” is another function and it takes only two arguments, what happened with my n-arguments from the rest parameter? it does some maths with only a and b.

My second question: The lesson afirms: With the rest parameter, you can create functions that take a variable number of arguments. These arguments are stored in an array that can be accessed later from inside the function.

So: Whenever I use the rest parameter, it creates an arraw with the values given to those parameter or with some kind of fixed parameters?

I wholeheartedly appreciate your support on this! Thanks!

first, reduce is an array method. You will met it later it in the curriculum, or you can search about it.

The rest parameter in the code you posted make so that args is an array containing all the arguments passed in the function. In this case, args is [1, 2, 3]
Then reduce from that array returns a single value.
What that value is depends on the function passed in. For more, check the documentation.

1 Like