Arguments Object in JavaScript

Posted on Nov 28, 2014


Arguments Pseudo Array

The array-like arguments object is automatically made available to you in every function. This is true whether you have defined any arguments when declaring the function or not. The arguments object contains a list of all the arguments you have passed in to the current function. Consider the following:

Using arguments gives us access to everything that was passed into the function.

Like an array, arguments has a .length property, and each arguments can be accessed via its index, so we can loop through them.

At this point, you may (rightfully) expect to be able to use arguments like a normal array. However, that’s where the similarities end. For example, a common use case is to grab a subset of the arguments, but this will not work:

The reason this produces an error is because arguments does not have a .slice() method, nor does it have .push(), .pop(), .split(), .join(), etc.

In fact, the arguments object only has two other properties: .callee and .caller. Those reference the currently invoked function and the function that invoked the currently invoked function respectively.

To get around this limitation of arguments, we have to borrow the .slice() method from the Array.prototype. If we do that, we create a new array containing the values of arguments, and we also get access to all the normal methods of array.

To perform this reassignment, we are going to use .call(). This will allow us to specify the object we wish to use the .slice() method on, as well as supply arguments to the .slice() method.

Submit a Comment

Your email address will not be published. Required fields are marked *