The arguments object is an Array-like object which represents the arguments passed in when executing a function. To convert it to Array, there are several methods that we are going to discuss in the scope of this article.
Array.from
There is method in ECMAScript 2015 that converts an arguments into an array. You can use the Array.from() or the spread operator like this:
Javascript converts an arguments into an array using Array.from method
The rest parameter syntax allows representing an indefinite number of arguments as an Array.
slice()
When the slice() method is called normally, it means that this is an Array, and the method iterates over that Array and works properly.
The this in the slice() function is accepted as an Array as when you call the following the object automatically becomes the value of this in the method():
object.method();
Let’s consider the following case:
[1,2,3].slice()
The [1,2,3] Array set will be as the value of this in slice().
But if you substitute something else, for example, that has a numeric .length property or a set of properties that are numeric indices as the this value, it should work. This kind of object is often called an array-like object.
The Array-like object means that arguments has a length property and properties indexed from zero, but it doesn't have the built-in methods of Array, such as forEach() and map().
The call() and apply() methods allow setting the value of this in a function manually. If you set the value of this in slice() to an array-like object, it will consider it as an Array, and perform the same action as in the case of arrays.
Let’s take a look at this example:
Javascript converts an arguments into an array using call method