DEV Community

Cover image for The Arguments Object in Javascript
Md Shahab Uddin
Md Shahab Uddin

Posted on

The Arguments Object in Javascript

In javaScript we are free to pass as many argument as we want and javaScript won't show us error. For example:

function multiply(x) {
    var result = x * 10;
    console.log(result);
}
multiply(5,7,8,9);  //50
Enter fullscreen mode Exit fullscreen mode

This code won't show error becuase javaScript avoids these extra arguments. But if we want,we can access them via an Object which is called arguments object.

Those parameters which are present in funciton definition can only be accessed by the parameter name.Other additional parameter will have to access throguh arguments object.
Let'see and example:

function wage(salary, month) {
    const total = salary * month;
    const invoice = total + arguments[0];
    console.log(invoice); 
}
wage(1000, 5, 1000);
Enter fullscreen mode Exit fullscreen mode

The output of the above funciton is 6000. IF you add more arguments , we also can access them throgh argument object.

Remember that It's not an Array , It's an arry like object which doesn't have any array like properties except length. You can calculate legth of the argument with arguments.length. For example:

function wage(salary, month) {
   console.log(arguments.length)
}
wage(1,2,3,4,5,6,7,8,9,10);  //10
Enter fullscreen mode Exit fullscreen mode

Althoguh arguments object don't have array properties and methods but we can convert them to array and use all the Array properties

4 ways to convert Argument Object to Array

First Method:

function wage(x,y) {
    return Array.prototype.slice.call(arguments);
}
wage(1, 2, 3); //[1,2,3]
Enter fullscreen mode Exit fullscreen mode

Second Method:
function wage(salary) {
return [].slice.call(arguments);
}
wage(1, 2, 3); //[1,2,3]
Third Method:

function wage(salary) {
    return Array.from(arguments);
}
wage(1, 2, 3); //[1.2.3]
Enter fullscreen mode Exit fullscreen mode

Fourth Method:
function wage(salary) {
return [...arguments];
}
wage(1, 2, 3); //[1.2.3]

I hope you now have a clear idea of converting this array like object to an actual array. You can also check type of arguments passed in the funciton. FOr example

function wage() {
    console.log(typeof arguments[0]); //Number
    console.log(typeof arguments[1]); //String
    console.log(typeof arguments[2]); //Object
    console.log(typeof arguments[3]); //Object 
}
wage(1, "John", ["A","B"],{age: 25,gender: "Male"});;
Enter fullscreen mode Exit fullscreen mode

Thanks for reading my article.

Top comments (0)