/ JTricks.com
/ Tutorials & Howtos
/ Varargs
Last updated: 19 Nov 2010
Using variable number of arguments (varargs) in Javascript functions
Javascript (especially being a dynamic language) supports calling functions with variable number of arguments.Unlike many other languages such as Java, it is not declared in any special way in function signature. In fact, any Javascript function is varargs (ability of a function to handle those arguments is a different question altogether)!
Calling Javascript function with variable arguments
Varargs functions are not declared in any special way. In fact, any function can receive any number of arguments irrespective of the number of parameters in its signature.function f(a,b) { // ... }can be called in any of the following ways:
-
f(1);
wherea
will contain1
andb
will be undefined. -
f(1, 2);
wherea
will contain1
andb
will contain2
. -
f(1, 2, 3);
wherea
will contain1
;b
will contain2
and3
will be accessible through special array-like object namedarguments
. - ...etc.
arguments
variable, which can be accessed like
an array, it has length
property and individual arguments will be retrievable as arguments[0]
,
etc.
Arguments array (or creating array from arguments object)
Variablearguments
is not an array though. It's an array-like structure. If full
Array
functionality is needed, this can be achieved in the following way:
var argumentsArray = Array.prototype.slice.apply(arguments);
Passing variable arguments to other functions
Variablearguments
(or any other array) can be passed to the other function by means of apply
.
For example:
function varargsFunction1() { // shows 3 alert("varargsFunction1 arguments length: " + arguments.length); // calls second varargs function keeping current 'this'. varargsFunction2.apply(this, arguments); } function varargsFunction2() { // shows 3 alert("varargsFunction2 arguments length: " + arguments.length); } varargsFunction1('a','b','c');First argument of
apply
function is the object that will be available as this
in called function. Passing (current) this
as the first argument will ensure that this
will remain the same in called function.
Callee
To make recursive calls, a function needs to refer to itself. For named functions this can be done through its name. Anonymous functions (which can be created with function expression or function constructor) don't have the name.The variable
arguments
also supports additional property, callee
,
which contains the function currently being executed. This allows to make recursive
anonymous functions (as those will be able to refer to themselves).
Note that
arguments.callee
will not work in ECMAScript 5
strict mode.