JavaScript Destructuring assignment Using rest parameters to create an arguments array

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!


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).

Got any JavaScript Question?