Rest & Spread part 1
ES6 Rest Parameters
Prior to ES6, if we wanted to pass a variablenumber of arguments to a function, we could use the arguments object, an array-like object, to access the parameters passed to the function.
For example, let's write a function that checks if an array contains all the arguments passed:
We can pass any number of arguments to the function and access it using the arguments object.
While this does the job, ES6 provides a more readable syntax to achieve variable number of parameters by using a rest parameter:
The ...nums parameter is called a rest parameter. It takes all the "extra" arguments passed to the function. The three dots (...) are called the Spread operator.
Only the last parameter of a function may be marked as a rest parameter. If there are no extra arguments, the rest parameter will simply be an empty array; the rest parameter will never be undefined.
Comments
Post a Comment