Thoughts from the office by Ed Ball
Friday, March 18, 2005

Normally you access function arguments by name.

function WriteAll(a, b)
{
  Write(a);
  Write(b);
}

However, you can also access function arguments by index using the special arguments object. This technique is particularly useful when implementing a function that takes an arbitrary number of arguments.

function WriteAll()
{
  for (var n = 0; n < arguments.length; n++)
    Write(arguments[n]);
}

The arguments object has a length property and one integer property for each argument (starting with 0, of course), but its similarity to Array ends there – it has none of the other methods of an Array. It is easy enough to convert an arguments object to an array; I use SliceArguments:

function SliceArguments(args, nStart, nEnd)
{
  if (nStart === undefined)
    nStart = 0;
  if (nEnd === undefined)
    nEnd = args.length;
  var aResult = [];
  while (nStart < nEnd)
    aResult.push(args[nStart++]);
  return aResult;
}

The arguments object has another useful property; the callee property returns the Function object that is being executed. This is primarily useful for recursion in anonymous functions, since there’s no function name to use. (I’ll talk more about anonymous functions in a future post.)

The arguments object has one more property: caller. It returns the Function object that called the currently executing function. However, the caller property has limited use, and has been deprecated in the most recent versions of JavaScript.

One more item of interest – each Function object has a length property that indicates the number of named arguments of that function.

function Blorb(a, b, c) {}
// Blorb.length == 3
3/18/2005 1:58:31 PM (Pacific Daylight Time, UTC-07:00) | Comments [1] | Code | JavaScript#
Search
Archive
Links
Categories
Administration
Blogroll