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 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.
You can see the arguments
object is a lot like an array, but it is not an actual array. Although it has the length
property, you can not use the common array methods like map()
, slice()
, and filter()
on it.
To convert an arguments
object to a true Array
object, there are several ways available that we are going to discuss below.
Rest Parameters
The rest parameter syntax was introduced in ES6 that allows us 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()
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 an 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()
Finally, the last method to convert an arguments
object to an array is by using the Array.prototype.slice()
method. Much like converting a NodeList to an array, Array
's slice()
method takes in the arguments
object and transforms it into an true 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 use them to store multiple pieces of information in one single variable, take a look at this guide.
✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.