Arguments object of JavaScript

From LQWiki
Jump to navigation Jump to search

JavaScript gives you, within a function code, access to the arguments the function was called with:

function sayHi() 
{
  if (arguments[0] == “bye”) 
  {
    return;
  }
alert(arguments[0]);
}

arguments.length delivers the number of arguments:

function howManyArgs() 
{
  alert(arguments.length);
}
howManyArgs(“string”, 45); //outputs “2”
howManyArgs(); //outputs “0”
howManyArgs(12); //outputs “1”

JavaScript code can be edited with a JavaScript editor. Unlike other programming languages, ECMAScript functions don’t validate the number of arguments passed against the number of arguments defined by the function; any developer-defined function accepts any number of arguments (up to 255, according to Netscape’s documentation) without causing an error. Any missing arguments are passed in as undefined; any excess arguments are ignored. By using the arguments object to determine the number of arguments passed into the function, it is possible to simulate the overloading of functions:

function doAdd() 
{
  if(arguments.length == 1) 
  {
    alert(arguments[0] + 10);
  } 
  else if (arguments.length == 2) 
  {
    alert(arguments[0] + arguments[1]);
  }
}
doAdd(10); //outputs “20”
doAdd(30, 20); //outputs “50”

The function doAdd() adds 10 to a number only if there is one argument; if there are two arguments, they are simply added together and returned. So doAdd(10) outputs “20” whereas doAdd(30,20) outputs “50”. It’s not quite as good as overloading, but it is a sufficient workaround for this ECMAScript limitation.