Pattern for JavaScript Options with Defaults


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( + ' and ' +;

Try running some demonstration code by clicking these buttons:

I hope somebody found that interesting/helpful.