ES6: Rest Parameter

5min read

The Rest Paramameter collects all the remaining elements into an array. It is the sibling of the Spread Operator and uses the same syntax of three dots “…” preceeding it.

Sum up function parameters

The typical usecase for the Rest Paramter is to sum up all remaining parameters of a function which we don’t want to specify. In this case we sum up all the adress data into one array.

Note: The Rest Parameter can only be used at the end after all other parameters have been specified.

If we want to output the adress as a String instead of an array we can use the Spread Operatorto do it.

Rest Paramter vs Arguments Object

Dont cofuse the Rest Paramter with the Arguments Object in Javascript. A short recap: The Arguments object allows us to access all arguments that have been passed into the function in form of an array-like object.

There are three main differences:

  • The arguments object contains all arguments passed to the function while the Rest Parameter only contains the one’s that haven’t been specified at the end of the parameters list.
  • The arguments object is in contrary to the Rest Parameter only an array-like object which means it inherits not the same methods (e.g. sort, map, filter) as a real array. The Rest Paramter is an instance of the Array Object and therefor has full access to all its methods.
  • the arguments object has additional functionality specific to itself (like the calleeproperty).

Rest Parameter in Destructuring

The Rest Paramater comes in really handy when used with Destructuring to collect all non-specified values in an array.

0 replies

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply

Your email address will not be published. Required fields are marked *