Function Arguments: The Arguments Object

Within the body of a function, the identifier arguments always has special meaning. arguments is a special property of the call object that refers to an object known as the Arguments object. The Arguments object is like an array that allows the argument values passed to the function to be retrieved by number, but it is not actually an Array object. The Arguments object also defines an additional callee property, described later.

Although a JavaScript function is defined with a fixed number of named arguments, it can be passed any number of arguments when it is invoked. The arguments[] array allows full access to these argument values, even when some are unnamed. Suppose you define a function f that expects to be passed one argument, x. If you invoke this function with two arguments, the first argument is accessible within the function by the parameter name x or as arguments[0]. The second argument is accessible only as arguments[1]. Furthermore, like all arrays, arguments has a length property that specifies the number of elements it contains. Thus, within the body of our function f, invoked with two arguments, arguments.length has the value 2.

The arguments[] array is useful in a number of ways. The following example shows how you can use it to check that a function is invoked with the correct number of arguments, since JavaScript doesn’t do this for you:

function f(x, y, z) { // First, check that the right number of arguments were ...

Get JavaScript: The Definitive Guide, Fourth Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.