Sitemap
c0d3r

c0d3r

The Arguments Object in Javascript

3 min readMar 10, 2016

In certain programming languages, if we defined a function to take in a certain number of parameters, and used the function with anything other than the requisite number of parameters, it will return a syntax error.

calling a function in Ruby with wrong number of arguments

In the above Ruby code, the compiler didn’t like that I passed two arguments in to function ‘a’ because I had defined it with only one argument.

In Javascript however, we’re free to pass in as many or as few parameters to a function as we wish.

moar arguments? no worries.

In the above Javascript code, I passed in 4 arguments to a function defined with only 1 argument. It just carries on with business as usual. This can actually be a useful feature because there is a way to access these other ‘undefined’ arguments.

All parameters passed in are accessed via the ‘arguments’ object, which is a reserved keyword. All parameters, both defined and undefined, will take their place in the object in order of appearance.

Only the parameters appearing in the function definition can be accessed by their parameter names. All additional parameters will have to be accessed through ‘arguments’.

Say we have a function a

var addOneToFirstArgument = function(x) {return x+1}

And we invoke it as

addOneToFirstArgument(1,2,3)

Then ‘arguments’ will be the object

[1,2,3]

and ‘x’ refers to ‘1’.

Get c0d3r’s stories in your inbox

Join Medium for free to get updates from this writer.

If we so desired, the trailing arguments can be accessed within the function body using the ‘arguments’ object:

arguments[1] // is 2arguments[2] // is 3

Here, they are not utilized so the function ignores them and returns 1+1 = 2. (The astute of you may be asking why the object looks like an array. Well, MDN says it’s an array-like object, so we can access its elements using array index notation as we shall see below).

Say we modify this function to add two numbers and for some obscure reason still insist on having only one parameter, it would look something like this

var addFirstTwoArguments = function(x) {return x+arguments[1]}

Notice because arguments is ‘array-like’, we can access its elements using array index notation.

Calling it like so

addFirstTwoArguments(1,2)

‘arguments’ will look like

[1,2]

where the first argument is aliased to ‘x’ within the function and the second argument has no alias in the function.

Now, the second argument, though not explicitly parameterized in the function definition, is accessed from within the function definition as the second element of ‘arguments’. So the function will return 1+2=3.

Note that the first argument was aliased as ‘x’ but it could equally well have been accessed as arguments[0] so an equivalent function definition would look like

var addFirstTwoArguments = function(x) {
return arguments[0]+arguments[1]
}

--

--