chris carter's web log

Home |  Contact |  Admin
 

Optional Parameters In JavaScript

Posted on October 20, 2008

I've found more and more uses for the optional parameters in javascript.  I have no idea if there's an actual name for this other than optional parameters, so i'm goin with it.

jQuery and prototype and I'm sure most if not all of the other cool "web 2.0"  libraries have a way of extending objects and have had these methods for a long time, so this is nothing new, I just am now finding more uses for it.  It usually entails copying the properties of one object over the properties of another.  I wrote a stand alone function copied from  prototype's Object.extend implementation that looks like this:

function extend(destination, source){
  for(prop in source){
    destination[prop] = source[prop];
  }
  return destination;
}
1
2
3
4
5
6

So let's say I have a function that has has 3 possible values that can be passed into it.  Most of the time I see methods like this:

function f(width,height,title){
//do stuff
}
1
2
3

The problem with this method is that all of params are required and none of them have default values.   Another way is using the built in arguments object (description taken from the ecmascript spec here-it's a pdf) like this:

function f(){
  var width = arguments[0] || 200;
  var height = arguments[1] || 500;
  var title = arguments[2] || 'Default Title';
  //do stuff
}
1
2
3
4
5
6

This accounts for not passing in all of the parameters and getting some default behavior, but they are based on position.  So in order to override the title, you'd need to pass in values for the first two params.

Optional Params Using extend

function f(){
  var options = extend({
    width: 200,
    height: 500,
    title: 'Default Title'
  }, arguments[0] || {});
  return options;
}
1
2
3
4
5
6
7
8

Using the extend method now, we can call the above method with any, all, or none of the parameters like this:

f(); //this would use all of the default values

f({ width:400 }); //override just the width

f({ title:'new title' }); //override just the title

f({ height:150,width:600 }); //override in any order
1
2
3
4
5
6
7

Here's a little test page that exercises this stuff: DefaultParams.htm

ASP.NET MVC Beta Source Code Is Posted On CodePlex

Posted on October 20, 2008

Yay, i was downloader number 7! Get it here.