JavaScript Using rest parameters to create an arguments array


If you ever need an array that consists of extra arguments that you may or may not expect to have, apart from the ones you specifically declared, you can use the array rest parameter inside the arguments declaration as follows:

Example 1, optional arguments into an array:

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

printArgs(1, 2, 'optional', 4, 5);
// -> "1, 2, ['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');
// -> "[1, 2, 'Arg #3'] true"

The console printed true because myArguments is an Array, also, the ...myArguments inside the parameters arguments declaration converts a list of values obtained by the function (parameters) separated by commas into a fully functional array (and not an Array-like object like the native arguments object).