Javascript - Using arguments objects

Introduction

You can define a function to accept any number of arguments and behave appropriately.

Consider the following:

function sum() { 
    if(arguments.length == 1) { 
        console.log(arguments[0] + 10); 
    } else if (arguments.length == 2) { 
        console.log(arguments[0] + arguments[1]); 
    } 
} 
sum(10);        //20
sum(30, 20);    //50

The function sum() adds 10 to a number only if there is one argument; if there are two arguments, they are added together and returned.

So sum(10) returns 20, whereas sum(30,20) returns 50.

Arguments object can be used with named arguments:

function sum(num1, num2) {
   if(arguments.length == 1) {
       console.log(num1 + 10);
   } else if (arguments.length == 2) {
       console.log(arguments[0] + num2);
   }
}

In the code above, two-named arguments are used with the arguments object.

The named argument num1 holds the same value as arguments[0], so they can be used interchangeably.

The values of arguments object stay in sync with the values of the corresponding named parameters. For example:

function sum(num1, num2) {
   arguments[1] = 10;
   console.log(arguments[0] + num2);
}

In the code above sum() overwrites the second argument with a value of 10.

The change to arguments[1] changes the value of num2.

This effect goes only one way: changing the named argument does not result in a change to the corresponding value in arguments.

If only one argument is passed in, setting arguments[1] to a value will not be reflected by the named argument.

The length of the arguments object is set based on the number of arguments passed in, not the number of named arguments listed for the function.

Any named argument that is not passed into the function is assigned the value undefined.

In strict mode, The value of num2 remains undefined even though arguments[1] has been assigned to 10.

And trying to overwrite the value of arguments is a syntax error in strict mode.

All arguments in ECMAScript are passed by value. It is not possible to pass arguments by reference.

Related Topic