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


Fatal error: Uncaught Error: Call to undefined function fetch_rss() in /var/www/ninjatool.dk/blog/wp-content/plugins/wp-cron/wp-cron-dashboard.php:18 Stack trace: #0 /var/www/ninjatool.dk/blog/wp-includes/class-wp-hook.php(298): wp_cron_dashboard('') #1 /var/www/ninjatool.dk/blog/wp-includes/class-wp-hook.php(323): WP_Hook->apply_filters('', Array) #2 /var/www/ninjatool.dk/blog/wp-includes/plugin.php(453): WP_Hook->do_action(Array) #3 /var/www/ninjatool.dk/blog/wp-content/plugins/wp-cron/wp-cron.php(62): do_action('wp_cron_hourly') #4 /var/www/ninjatool.dk/blog/wp-includes/class-wp-hook.php(298): wp_cron_hourly_exec('') #5 /var/www/ninjatool.dk/blog/wp-includes/class-wp-hook.php(323): WP_Hook->apply_filters(NULL, Array) #6 /var/www/ninjatool.dk/blog/wp-includes/plugin.php(453): WP_Hook->do_action(Array) #7 /var/www/ninjatool.dk/blog/wp-includes/load.php(677): do_action('shutdown') #8 [internal function]: shutdown_action_hook() #9 {main} thrown in /var/www/ninjatool.dk/blog/wp-content/plugins/wp-cron/wp-cron-dashboard.php on line 18