Skip to content

JavaScript arguments to array

  • by

In JavaScript, the “arguments” object is an array-like object that contains the values of the arguments passed to a function. To convert the “arguments” object to a real array, you can use the spread operator, the Array from() method, or the Array slice() method.

JavaScript arguments to array example

Simple example code.

1. Using the spread operator:

You can use the spread operator (…) to convert the “arguments” object to an array. Here’s an example:

function myFunction() {
  const args = [...arguments];
  console.log(args);
}

myFunction(1, 2, 3);

Output:

JavaScript arguments to array

2. Using the Array.from() method:

You can use the Array.from() method to convert the “arguments” object to an array. Here’s an example:

function myFunction() {
  const args = Array.from(arguments);
  console.log(args);
}

myFunction(1, 2, 3);

Array.prototype.slice() method:

You can use the Array.prototype.slice() method to convert the “arguments” object to an array.

function myFunction() {
  const args = Array.prototype.slice.call(arguments);
  console.log(args);
}

myFunction(1, 2, 3); 

Comment if you have any doubts or suggestions on this JS arguments topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Your email address will not be published. Required fields are marked *