Thursday, 10 November 2011

Set Default Parameters in JavaScript using jQuery

When you create a JavaScript function with multiple parameters, it can get a little bit messy.

Consider this JavaScript function:
init_spinning : function(lines, length, width, radius, colour, speed, trail, shadow) {
  var opts = {
    lines: lines,
    length: length,
    width: width==null? 5,
    radius: radius==null? 8
    etc..
  }
}

Usage example:
init_spinning(8, 4, null, null, '#20CNSE', 1.6, 30, false);

Yuck! Not only do you have to remember which ones are mandatory, but also this is error prone.

Using jQuery's $.extend() function, we could use:
init_spinning : function(options) {
  var opts = $.extend({
    lines: 8,
    length: 5,
    width: 7,
    radius: 7,
    color: '#26BCED',
    speed: 1.3,
    trail: 44,
    shadow: false
  }, options||{});
  etc..
}

Usage example:
init_spinning({
  length: 3,
  width: 3,
  radius: 3
});

Much better! In the above example, the function has default values for all the parameters, and you just assign the ones that you need!
blog comments powered by Disqus