I am Hack Sparrow
Captain of the Internets.

JavaScript – Convert arguments to Array

How to convert arguments to JavaScript 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 looks 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. You might like to read this post for more details on call().

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

Make a Comment