Note: The Console blog is no longer active. I'm currently building the Sculpted Code blog, and when it's finished, I shall be posting there.
← Console Index
Creating Functions with Optional Arguments in Javascript

In this post, I will show you how to create functions with optional arguments, or parameters, in Javascript. For example, in our demo function doSomething, the user can specify an “onComplete” function to call when finished “doing something”, but doesn’t have to specify one if is not needed.

First, we declare our function:

function doSomething()
{
 // Code to do something...
}

Note that we do not include the “onComplete” argument in the function declaration. If we did this, then the user would be required to supply a value for the “onComplete” argument (and if they didn’t, there would be an error).

Javascript has an “arguments” array for each function, containing (logically) all the arguments passed in by the user. We can use this to implement optional arguments, as long as we know the order of the optional arguments (in this case, we don’t have to worry, since there is only one optional argument):

if (arguments.length > 0) {
 var onCompleteFunction = arguments[0];
}

Here, we check to see if the arguments array contains anything, and if there is, get the first item (which will be the “onComplete” function) and assign it to a variable named “onCompleteFunction”.

When we’ve finished “doing something”, we can see whether there is an onCompleteFunction variable, and if so, call the function contained by the variable:

if (onCompleteFunction)
 onCompleteFunction();

Note: Since the if statement only has one line of code, we can omit the opening and closing braces to make it as simple as possible.

And there it is! The final function should look similar this:

function doSomething()
{
 if (arguments.length > 0) {
  var onCompleteFunction = arguments[0];
 }

 // Code to do something…

 if (onCompleteFunction)
  onCompleteFunction();
}

The user can then call it like this:

doSomething();

…or like this:

doSomething(function() {
 alert("Done!");
});

Either one of these is valid, and will not produce any errors.