Here's a trick I learned from Valerio (author of Mootools) on how to handle options for classes and functions. After refactoring a couple of legacy scripts I thought I'd share for those of you who might not know it already. This example below uses the Mootools syntax for class creation, but the rest of it can be used even on its own I think.

So let's say you have a class that takes numerous options but you want to set up some defaults. Even for the values that you don't want to be default, you want to make sure they are defined. Here's how you can write your code to do all of that clearly and easily:

JavaScript:
var exampleObject = new Class ({
    initialize: function(options) {
        this.options = Object.extend({
            items: [],
            start: 0,
            stop: -1
        }, options || {});
       
        this.execute();
    },
    execute: function(){
        if(this.options.stop <0 || this.options.stop> this.options.items.length) this.options.stop = this.options.items.length;
        //let's not use items.each here because we want to set a start and stop index
        for(i = this.options.start; i <this.options.stop; i++){
            alert(this.options.items[i]);
        }
    }
});

drag to resize


In this simple example, we could initialize one of these objects like so:

JavaScript:
var myObject = new exampleObject();

drag to resize


and nothing would happen because the items in the options are an empty array, but it wouldn't break. If we did this instead:

JavaScript:
var myObject = new exampleObject({
    items: ['one', 'two', 'three']
});

drag to resize


You'll get an alert for one, two, and three. start remains at index 0, and stop defaults to the length of the array.

JavaScript:
var myObject = new exampleObject({
    items: ['one', 'two', 'three'],
    start: 1
});

drag to resize


Now we'll only get alerts for two and three.

JavaScript:
var myObject = new exampleObject({
    items: ['one', 'two', 'three'],
    start: 1,
    stop: 2
});

drag to resize


And here we'll only get an alert for two and three.