How to convert arguments object to an array in JavaScript

published: 26 May 2022

2 min read

How to convert arguments object to an array in JavaScript

The arguments object is an array-like object accessible inside all non-arrow functions that represents the values of the arguments passed to that function. You can use numerical indexes to access the values of arguments from the arguments object. For example, the first argument can be accessed as arguments[0], the second argument can be accessed as arguments[1], and so on.

The arguments object is a lot like an array, but it is not a real array. Although it has the length property, you can not use the common array methods like map(), slice(), and filter() on it.

There are multiple ways to convert an arguments object to a true Array object.

Rest Parameters

The rest parameter syntax was introduced in ES6 to represent an unspecified number of arguments as an array. To use rest parameters, you can prefix the function's last parameter with ... (spread operator). It will convert all remaining user-supplied arguments into a standard JavaScript array.

Since the rest parameter is a real Array instance, unlike the arguments object, you do not need to perform any conversion:

const sort = (...numbers) => {
  return numbers.sort((a, b) => a - b)
}

sort(1, 4, 5, 2)
// [ 1, 2, 4, 5 ]

Array.from() Method

Another way to convert the arguments object to an array in ES6 is by using the Array.from() method. This method converts an array-like or iterable object into an Array instance:

function sort() {
  return Array.from(arguments).sort((a, b) => a - b)
}

sort(1, 4, 5, 2)
// [ 1, 2, 4, 5 ]

Array.prototype.slice() Method

Finally, the last method to convert an arguments object to an array is the Array.prototype.slice() method. Much like converting a NodeList to an array, the Array.slice() method takes in the arguments object and transforms it into an actual array:

function sort() {
  const args = Array.prototype.slice.call(arguments)
  return args.sort((a, b) => a - b)
}

const sorted = sort(1, 4, 5, 2)

console.log(sorted)
// [ 1, 2, 4, 5 ]

You can also use a concise form of the slice() method:

const args = [].slice.call(arguments)

The Array.prototype.slice.call() works in all modern and old browsers, including IE 6+. You should use this approach if you want to support old browsers.

To learn more about JavaScript arrays and how to store multiple pieces of information in one single variable, read this guide.

How to convert arguments object to an array in JavaScript | Coding Tips And Tricks

Are we missing something?  Help us improve this article. Reach out to us.

Are you looking for other code tips?

Check out what's on in the category: javascript, programming
Check out what's on in the tag: javascript, programming, array