About JavaScript's arguments object and how it works..

·

2 min read

About JavaScript's arguments object and how it works..

Table of contents

No heading

No headings in the article.

The arguments object is an object that is created for every function by default. It takes the list of arguments that were passed while calling the function. Each argument that is passed to the function can be accessed by its index starting from 0th index just like an array. Let us understand this with the help of an example :

In the following code we have a function named showMyName() which takes two argument values namely "Jyotirmoy" and "Das" for firstName and lastName respectively.

function showMyName(firstName, lastName){
   document.write(firstName);
   document.write(lastName);
}
showMyName("Jyotirmoy ", "Das");

// Output : Jyotirmoy Das

The same can be achieved with the help of arguments object as shown in the following code :

function showMyName(firstName, lastName){
   document.write(arguments[0]);
   document.write(arguments[1]);
}
showMyName("Jyotirmoy ", "Das");

// Output : Jyotirmoy Das

The important thing to note here is that the arguments object behave just like an array (starting at 0 index) while accesing the arguments from the arguments list.

The above example can also be written without the arguments firstName and lastName within the function parameter section and still can be obtained the same output. Check this code below :

function showMyName(){
   document.write(arguments[0]);
   document.write(arguments[1]);
}
showMyName("Jyotirmoy ", "Das");

// Output : Jyotirmoy Das

With arguments object we can also get the length of the arguments list. It gives us the total elements present in the arguments list. For example :

function showMyName(firstName, lastName){
    document.write(arguments.length)
}
showMyName("Jyotirmoy ", "Das");

// Output : 2

In the above example we have passed two elements, therefore the arguments object returns us the length of the arguments list which is 2 (two). This should not be confused with the number of parameters that are prepared by the function i.e., firstName and lastName. the parameters does not come into scene while counting the length of the arguments. Check out the example below :

function showMyName(firstName){
    document.write(arguments.length)
}
showMyName("Jyotirmoy ", "Das");

// Output : 2

In the above scenario, we can clearly see that the number of parameters in the function is one (firstName), and number of arguments are two ( "Jyotirmoy" and "Das" ) and the arguments.length points to the arguments list and not to the parameters list. Thus the parameter list does not affect the arguments list in this case.