Using Variable Length Arguments With JavaScript

Variable Length ArgumentsThere are times when you simply don't know how many arguments a function will be receiving. Some languages handle this sort of problem with function (or method) overloading-defining a function multiple times with each function definition containing a different number (or type) of parameters. With JavaScript, you can code one function that can dynamically handle different function definitions. Here's how.

When you pass parameters into a function in JavaScript, the function itself has a property called arguments. This property is actually an array that contains all of the arguments that were passed into the function. Let's take a look at some example code:


function Something()
{
var ArgumentCount;
var ArgumentValues;
var Value1;
var Value2;
var Value3;

ArgumentValues = Something.arguments;
ArgumentCount = Something.arguments.length;

Value1 = (ArgumentCount > 0) ? ArgumentValues[0] : null;
Value2 = (ArgumentCount > 1) ? ArgumentValues[1] : null;
Value3 = (ArgumentCount > 2) ? ArgumentValues[2] : null;

if (Value2 != null)
// Do Something
}


We'll walk through the code. First you'll see we create two variables, ArgumentValues and ArgumentCount and we'll assign them to the arguments array for the function, and the length of the arguments array respectively.

Next we process out our parameters. We create three variables, Value1, Value2 and Value3. For each one we use the conditional "?" operator. Although you don't see it too often, this operator is a shortcut for if/then/else. It basically says if the first item is true, then do what follows the "?", else do what's after the ":".

In each case we check to see if the length of the arguments array is greater than a certain value(if there is a second parameter for example) and if so-set the variable to that entry in the arguments array. If the parameter doesn't exist, we set the variable to null and can check it later.

With this code, it makes it easy to create a function that can handle any number of parameters.

0 comments: