I am BARRY HESS > Blog

JavaScript Optional Parameter Hash With Default Values

I have dealt with optional parameters with default values in JavaScript plenty of times in the past. But for some reason it wasn’t immediately obvious to me how to create a nice options hash like I use so frequently when writing my Ruby code. It really is quite simple.

Here are the beginnings of a little function to handle the changing of a timeframe in a dropdown. The very obvious key is to default your options parameter to an empty hash if it comes through as null/undefined. I’m not sure why that eluded me for a while this afternoon. I’m defaulting the possible options in a couple different ways. I’m checking if boolean options are defined before defaulting them. For string options, I’m simply using an || operator.

function on_timeframe_change(options){
  options  = options || {};
  var hide_selector_on_custom = typeof(options['hide_selector_on_custom']) == 'undefined' ?
    false :
    options['hide_selector_on_custom'];
  var prefix = options['prefix'] || '';
  var grab_focus = typeof(options['grab_focus']) == 'undefined' ?
    true :
    options['grab_focus'];

  . . .

}

Sorry if you cannot handle ternary operators.