Javascript Functions optional parameters

By | 20 May, 2014

Ok, you want to create a function to be used several times (well, isnt that the main purpose of them?), but, depending on the call, you can have 1 argument or several. How do you go about doing it? Enter the world of optional parameter functions. Or something like that…after the jump.

Here are three ways:

1. you create a function and verify if the arguments are undefined:

function showID(name,address){

   if(name==undefined){ name='unknown name'; }
   if(address==undefined){ address='no address'; }
   alert(name+" - "+address);

}

// calling the function with only one argument, for example:

showID('peter'); // shows an alert saying "peter - no address"

Alternative using || (OR):


function showID(name,address){

   name = name || 'unknown name';
   address= address || 'no address';
   
   alert(name+" - "+address);

}

// calling the function without 'address':

showID('john'); // shows an alert saying "john - no address"

Note that with this method only the last arguments can be optional, and you cant check for false values, unless you use the undefined approach (but with that you cant check for undefined…).

2. Using the arguments variable

function showID(){

   alert(JSON.stringify(arguments));

}

// calling the function with one argument:
showID('mary'); // shows an alert saying {"0":"mary"}

// calling the function with three arguments:
showID('mary',34,'sidney'); // shows an alert saying {"0":"mary","1":34,"2":"sidney"}

All javascript functions have an implicit arguments object when called, so you get arguments[0], arguments[1], etc. for your use.

3. Object literal

function showID(nome, stuff) {
    var stuff = stuff || {};
    var address = stuff.address || 'no known address';
    var phone = stuff.phone || 'no phone';

}
showID("paul", { address: 'street 3', phone: '555-1083' });
showID("garfunkel");

This is a nice flexible method for optional parameter..ing.

This knowledge was taken mainly from this great article by Mark Hansen (go read it, it is much better explained than this one :-):

Optional parameters in javascript