javascript

arguments object in JavaScript function

The arguments object is an Array-like object matching to the arguments passed to a function. The arguments object is a local variable available within all (non-arrow) functions. You can refer to a function’s arguments within the function by using the arguments object.Let’s consider below code:

function addition(num1, num2) { 
  return num1 + num2; 
} 
addition(10,20);

In above code, we are calling function “addition()” passing 10 and 20 for “num1” and “num2”. So, the function will return an answer 30. Now what if we pass one more arguments while calling function “addition()”? Let’s do it:

function addition(num1, num2) { 
  return num1 + num2; 
} 
addition(10,20,25);

Will this function “addition()” throw an error? Answer is no. It will return an answer 30. So, here comes one more question. What happen to the value 25? Answer is, it will be there in arguments object.

Let’s consider below code to access all the passed arguments using arguments object

function addition(num1, num2) { 
  return arguments[0] + arguments[1] + arguments[2]; 
} 
addition(10,20,25);

In above code, we are able to access all the passed arguments and the function “addition()” will return an answer 55 here. In JavaScript we can access all the passed arguments using arguments objects and this object contains an entry for each argument passed to the function, the first entry’s index starting at 0.

arguments object is an array-like object

In above example we can see the code where we are accessing arguments object same as we access an array. But we can’t say arguments object a pure array, because it does not provide all the properties which array provides. It provides only length property which make it an array-like object. If you will try anything else than length in arguments object it will throw an exception calling “…is not a function”.

Modify an arguments object

We can modify or set an value to the arguments object. Refer below code:

function addition(num1, num2) { 
  arguments[0] = 5;
  return arguments[0] + arguments[1] + arguments[2]; 
} 
addition(10,20,25);

We have used same code as our previous example, here we are setting first argument to the number 5 and it will get updated. So, this function “addition()” will return an answer 50.

Convert arguments object to a pure array

As we discussed, arguments object is not an array, but it is array like object. So, how to convert it to the pure array. Let’s consider below code

var args = Array.prototype.slice.call(arguments);

OR

var args = [].slice.call(arguments);

In ECMAScript 6 we can achieve same as below

var args = Array.from(arguments);

We can also do it using spread operator

var args = [...arguments];

Interested in JavaScript? Click here to read more JavaScript articles in Code4Developers

Leave a Reply