Last Updated: 23 May 2008

   |   

Author: dordal

Optional Parameters and Default Arguments

JavaScript supports optional parameters and default arguments to functions, but only supports the latter with a bit of a hack.

Optional parameters are easy. Just define a function to and then don't pass all the parameters:

function testFunction(a,b,c) {
   document.write(a + " ");
   document.write(b + " ");
   document.write(c + " ");
}

testFunction('foo','bar');   // will print 'foo bar undefined '

Of course, your function must handle those undefined parameters. You might want to set defaults for any parameters that are undefined; to do this, just check if they
are undefined:

function testFunction(a,b,c) {
   // this says 'if the type of a is undefined, set it to '', otherwise set it 
   // to a (e.g. itself)'
   a = (typeof(a) == undefined) ? '' : a;   
   b = (typeof(b) == undefined) ? '' : b;     
   c = (typeof(b) == undefined) ? '' : c;
}

One other thing that you can do is check the length (or values) of the arguments array. The arguments array is set inside each function, and contains a list of the arguments passed to the function.

Discussion

Enter your comment. Wiki syntax is allowed: