JS: Functions
Theory: Rest parameter syntax (packing arguments)
Let's try to implement a very simple function that sums up the numbers. First, let's define the sum() function, which takes two numbers as input and returns their sum:
So far, everything is simple and straightforward. Difficulties arise with additional requirements: what if we want to sum up not two but three numbers? Or five, or even ten? Writing a separate function to handle each case is obviously a bad idea:
It is necessary that a single function can work with a different number of arguments. How do you do that?
You may notice that there are functions in the standard JavaScript library that can take different numbers of arguments. For example, the signature of the Math.max() function is defined as follows:
It tells us that you can pass any number of elements to Math.max() and they are optional:
In terms of calling, nothing unusual, just a different number of arguments. But the definition of a function with a variable number of arguments looks unusual:
The colon character ... before a formal parameter name in the function definition denotes a rest operator. Writing ...params in the func() definition from the example above literally means the following: "place all arguments passed in the function call into the params array".
If no arguments are passed at all, the params array will be empty:
You can pass any number of arguments to a function - all of them will go into the params array:
Arguments can be of any type - numbers, strings, arrays, etc:
Now we have enough knowledge to rewrite our sum() function using the rest operator so that it can sum any number of numbers (not just two numbers, like now):
In that context, an array can be thought of as "optional arguments" that you can either not pass at all or pass as many as you want. But what if we want a function to have two ordinary ("required") named parameters and the rest to be optional and stored in a rest-array? It's simple: when defining a function, we first specify the standard named formal parameters (e.g., a and b) and add a rest-array at the end:
The same can be done for a single argument:
and for three:
This idea can go on and on, making as many arguments as required mandatory. The only restriction: the rest operator can only be used for the last parameter. That is, such code is syntactically incorrect:
That one, too:
This is why the operator is called rest, that is, it organizes the storage of the "rest" ("remaining", last) parameters.

