Pattern for JavaScript Options with Defaults

published:
2009.05.14
topics:
javascript

Maybe this is obvious, but here's a really handy pattern for passing an object of options into your JavaScript functions when you also want there to be a set of default options for that function. I'm using jQuery's $.extend function to handle the objects, but most JavaScript libraries provide this functionality.

function myFunction(arg1, options) {
	var defaultOptions = {
		foo: 'foo-default',
		bar: 'bar-default'
	}
	
	if (typeof options == 'object') {
		options = $.extend(defaultOptions, options);
	} else {
		options = defaultOptions;
	}
	
	// rest of your code here...
	
	// for demonstration purposes
	alert(options.foo + ' and ' + options.bar);
}

Try running some demonstration code by clicking these buttons:

I hope somebody found that interesting/helpful.