Javascript Tricks, Samples, Tutorials & Howtos

New versions notifications available via

Follow jtricksdotcom on Twitter
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); where a will contain 1 and b will be undefined.
  • f(1, 2); where a will contain 1 and b will contain 2.
  • f(1, 2, 3); where a will contain 1; b will contain 2 and 3 will be accessible through special array-like object named arguments.
  • ...etc.
When function with named parameters is called, first passed arguments will be available as variables with those names but all of the arguments will be placed into 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)

Variable arguments 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

Variable arguments (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.