How to use function named arguments in Javascript

Description

The function arguments object can work together with named arguments:


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

Example

arguments' values stay in sync with named parameters.


function doAdd(num1, num2) {/*from ww  w  .j  a va2  s . c  o  m*/
    arguments[1] = 10;
    console.log(arguments[0] + num2);
}
doAdd(1);
doAdd(1,2);

The code above generates the following result.

Note

This effect goes only one way. Changing the named argument does not change the corresponding value in arguments.

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

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





















Home »
  Javascript »
    Javascript Introduction »




Script Element
Syntax
Data Type
Operator
Statement
Array
Primitive Wrapper Types
Function
Object-Oriented
Date
DOM
JSON
Regular Expressions