passing false when the default is true

Lately, inspired by the prototype and scriptaculous libraries, I’ve frequently been defining JavaScript functions that accept an anonymous options object, so they can be called like this:

mynamespace.myFunction(requiredParam1, requireParam2, {
customCallback: mynamespace.myOtherFunction

And I’ve gotten fond of boolean short-circuits for parsing the options object and assigning defaults:

options.overrideSomeDefault = options.overrideSomeDefault || false;

Since everything except null, 0, “”, NaN, and undefined is “truthy” in JavaScript (see Simon Willison’s great presentation “A (Re)-Introduction to JavaScript” either as pretty slides or texty notes) this is fast, terse, and readable.

Unless for some reason you explictly need to pass one of the “falsey” values. I hit this first trying to make an autocompleter library work the way I wanted it to, something along these lines:

autocompleter {
init:function(_target,_callback,options) {
options = options || {};
options.minCharsToMatch = options.minCharsToMatch || 1;

Oops, I was stuck with minCharsToMatch of 1, which is not what I wanted.

I also think there are times when it makes more sense for a property to have a default value of true than false. It’s clearer (imo) for “enabled” to default true than for “disabled” to default false.

Here’s my attempt at a solution. If it’s reasonable to expect a “falsey” option value, you can do this:

option.aBool = ("undefined" != typeof option.aBool ? option.someBool : true);

Not as pretty, and not as fast. But should get the job done.

Leave a Reply