Warning: Declaration of GTranslate::widget($args) should be compatible with WP_Widget::widget($args, $instance) in /var/www/ninjatool.dk/blog/wp-content/plugins/gtranslate/gtranslate.php on line 0
JS: Optional parameter default true | NinjaTool inc.

JS: Optional parameter default true

Posted by on December 23, 2013

Just a short note: If you want to have an optional boolean parameter and have the default value to be false, you can use the property of a boolean to be false if it’s either undefined, null, 0 or false, so just evaluating opt_booleanParameter would evaluate to false it the parameter is omitted (I use that all the time). But if you really need the parameter to be type boolean, just slap a couple of !’s in front and it will evaluate to the boolean value false if omitted. E.g.

example = function(opt_booleanParameter) {
   var booleanParameter = !!opt_booleanParameter;

   if (booleanParameter) {
      // This point is ONLY hit if the optional parameter is provided and true.
   }
};

But if you want the default value to be true, I had a tendency to make the logic far longer than it needed to be. I usually use Google Closure, but with or without goog.isDef(), the assignment can be equally simple:

example = function(opt_booleanParameter) {
   var booleanParameter = opt_booleanParameter || opt_booleanParameter === 'undefined';

   if (booleanParameter) {
      // This point is now hit if optional parameter true or is omitted.
   }
};

(as indicated; the opt_bp === 'undefined' can be replaced with !goog.isDef(opt_bp) if you use the closure libraries. It does the exact same thing.)

 

EDIT: Thanks to my buddy, Ole at Rocha.dk, I added the ‘s to the ‘undefined’ comparison for increased cross browser compatibility.

160 Responses to JS: Optional parameter default true