How to convert arguments to an Array#

All JavaScript functions have a local variable called arguments, which is a list of arguments that were passed to the executing function. The first argument can be accessed as arguments[0], the second one as arguments[1] etc. To find out the numbers of arguments you can do arguments.length.

You can see arguments is a lot like an array. I say it is a lot like an array because it actually is not an array at all, it is an array-like object. You can access the items using a numerical index and it has a length property, but it is not an array.

arguments is actually structured like this:

{0: 'tiger', 1: 'jungle', length: 2}

not like this:

['tiger', 'jungle']

As long as you are limited to accessing the the items using an index and finding out the length of the arguments, you are a happy coder, but you have a problem when you want to call true array methods on arguments. If you plan on using arguments like an array in more than once instance, it best to convert it into an real array. Here is the way to do it:

arguments = Array.prototype.slice.call(arguments);

Now arguments is a real array and you can call all the array methods like slice(), splice(), map() etc. You may see code examples doing Array.prototype.slice.call(arguments, 0) instead of Array.prototype.slice.call(arguments), they are one and the same - when you don't pass any index to slice(), it is understood as 0.

In case you are interested in how the solution works, we used JavaScript's functional programming function call() to assign Array's slice() method temporarily to arguments and created an array containing the items of the argument array-like object.

Any method of converting arguments to array using loop should be avoided, because it is inefficient and way slower.

You can see the above concepts demonstrated in the editable example below:

Run
Clear

arguments's' length property is not being logged because it is not an enumerable property.

References#

  1. JavaScript: Array-like objects
  2. MDN - Function arguments
  3. MDN - Array
  4. MDN - Array-like objects
Tweet this | Share on LinkedIn |