Rest Operator
What is Rest Parameter?
The ES6 version provides a new parameter type called Rest Parameter which is prefixed with three dots ( ...).
Rest Parameter (also known as the representation of the remaining parameters) allows you to represent an infinite number of arguments as an array.
The syntax for using Rest Parameter:
The last parameter (args) that begins with an ellipsis ( ...
) is called Rest Parameter ( ... args
).
All the arguments you pass into the function will map to the parameter list.
In the above syntax, the first argument maps to a
, the second argument maps to b
, and the third, fourth, ... arguments will be stored in Rest Parameters args
as an array.
For example:
At this point, the parameter args
will contain the following values:
If you pass only the first two parameters, the remaining parameters will be an empty array:
... then arg sit would be:
However, the Rest Parameter must be at the end of the argument list, otherwise, it will cause an error:
Some examples using Rest Parameters in JavaScript
To understand Rest Parameter better, let's do some examples.
For example, suppose we want to add many numbers (but it is unclear how many numbers there are). We use Rest Parameters as follows:
Running the program we get the results:
n this example, args
it's an array, so we can use a loopfor of
to iterate over its elements and sum them up.
Suppose the function Sum()
can pass arguments with many different data types such as numbers, strings and booleans... But what if you just want to sum the numbers?
Simply, before adding, we check its type:
Then if you have arguments that mix up the data, it can still be calculated:
Result:
Or use the sublime way by combining the filter() function and reduce() function like this:
However, the arguments object itself is not an instance of the Array type, so you cannot use the method directlyfilter()
. In ES5 you must useArray.prototype.filter.call()
the following:
As you can see, using Rest Parameters as in the first example makes the code much more compact. Let's say you need to filter arguments based on a specific type like number, string, boolean, and null.
Result:
Rest Parameters and Arrow Functions
Arrow Function has no argument object, so if you want to pass some arguments to an arrow function, you must use Rest Parameter.
For example:
Result:
Rest Parameters and Dynamic Functions
JavaScript allows you to create dynamic functions via constructor . And Rest Parameter can be used in a dynamic function.
Here is an example:
Result:
Last updated