Using the Rest Parameter

A rest parameter is defined using the ellipsis (...) to signify that that parameter is a placeholder for any number of arguments. The rest parameter directly addresses the issues with arguments. First, it stands for the rest of the parameters and so is highly visible in the parameter list. Second, the rest parameter is of Array type. Let’s convert the max() function from the previous example to use a rest parameter.

 const​ max = ​function​(...values) {
  console.log(values ​instanceof​ Array);
 
 let​ large = values[0];
 
 for​(​let​ i = 0; i < values.length; i++) {
 if​(values[i] > large) {
  large = values[i];
  }
  }
 
 return​ large;
 };
 
 console.log(max(2, 1, 7, 4));

The two versions of max, the one that uses arguments and the one that uses a rest parameter named values, look almost identical. First, instead of an empty parameter list, we have ...values—the rest parameter name is prefixed with the ellipsis. Second, anywhere arguments appeared in the code, now there is values. At first sight, the rest parameter greatly improved the method signature and left the rest of the function mostly unaltered, except for the variable name change. Let’s look at the output of this code before discussing further:

 true
 7

The output shows that the rest parameter is an Array. This means we can use better, more fluent, and expressive functions on the rest parameter than we could ever use on arguments. For example, we can easily change the code to the following functional style:

 const​ max = ​function​(...values) {
 return​ values.reduce((large, e) => large > e ? large : e, values[0]);
 };

You will learn about the functional style later in this book. For now, we can appreciate how concise this code is, thanks to the fact that the rest parameter is of Array type; we can’t call methods like reduce() directly on arguments.

JavaScript has some reasonable rules for the rest parameter:

  • The rest parameter has to be the last formal parameter.
  • There can be at most one rest parameter in a function’s parameter list.
  • The rest parameter contains only values that have not been given an explicit name.

Overall the rest parameter is one of the good changes to the language. It makes a very powerful feature of receiving a variable number of arguments civil and sensible from both the syntax and the semantics point of view.

The ellipsis symbol used for the rest parameter on the receiving end can also be used on the function call side; let’s explore that next.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset