How to access function arguments in Javascript
Description
A Javascript function doesn't care the number and type of its arguments.
A function with two arguments defined can accept two, one, three or none arguments, since function arguments in Javascript are represented as an array internally.
The arguments object acts like an array.
The first argument is arguments[0]
, the second is arguments[1]
, and so on.
Example
To determine how many arguments were passed in, use the length
property.
function howManyArgs() {/* w w w . j av a 2 s . c o m*/
console.log("Hello " + arguments[0] + ", " + arguments[1]);
console.log(arguments.length);
}
howManyArgs("string", 45); //2
howManyArgs(); //0
howManyArgs(12); //1
The code above generates the following result.
Note
Any named argument that is not passed into the function is assigned the value undefined
.
All arguments in Javascript are passed by value. It is not possible to pass arguments by reference.