convert arguments to array javascript

How to Convert Arguments to Array in JavaScript

If you want to convert the arguments passed to a function into an array in JavaScript, you can use the built-in Array.from() method or the spread operator (...). Let's take a look at both methods:

Using Array.from()


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

myFunction('hello', 123, true); // Output: ['hello', 123, true]
  

In the example above, we define a function called myFunction() and pass in three arguments. Inside the function, we use the Array.from() method to create an array from the arguments object. We then log the resulting array to the console. The output will be an array containing the three arguments passed to the function.

Using the Spread Operator


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

myFunction('hello', 123, true); // Output: ['hello', 123, true]
  

In this example, we define the same function as before, but this time we use the spread operator (...) to convert the arguments object to an array. We then log the resulting array to the console. The output will be the same as before.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe