Using rest parameters to create an arguments array

suggest change

A rest parameter collects arguments that were not named individually. It must be the last parameter. The result is an Array, not the array-like arguments object.

Example 1, optional arguments into an array:

function printArgs(arg1, arg2, ...theRest) {
  console.log(arg1, arg2, theRest);
}

printArgs(1, 2, 'optional', 4, 5);
// logs 1, then 2, then ['optional', 4, 5]

Example 2, all arguments are an array now:

function printArgs(...myArguments) {
  console.log(myArguments, Array.isArray(myArguments));
}

printArgs(1, 2, 'Arg #3');
// logs [1, 2, 'Arg #3'], then true

Array.isArray(myArguments) is true. The arguments object is not an Array.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents