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:

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:

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

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:

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

In ECMAScript 6 we can achieve same as below

We can also do it using spread operator

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

Yatendrasinh Joddha
I am a software engineer currently living in Gandhinagar, India. My interest is in web and software development. I am also interested in sharing my knowledge with people.

I have expertise in and related Microsoft technologies, with JavaScript frameworks and libraries like JQuery, KnockOut.js,and AngularJS.
Yatendrasinh Joddha on FacebookYatendrasinh Joddha on GithubYatendrasinh Joddha on LinkedinYatendrasinh Joddha on TwitterYatendrasinh Joddha on Wordpress

Leave a Reply

%d bloggers like this: