Friday, August 20, 2010

The smallest boolean in JavaScript

One of my projects has a pretty large API, with lots of methods returning boolean values. At first, I returned 1's and 0's - which are not actual booleans, but are certainly good enough (for most applications). However, for a public API, I knew they would need to return true or false... After making the edits, my file size jumped. Which is how I found the smallest boolean in JavaScript.

JavaScript coders have used boolean variations and equivalents since the language's inception. No matter an object's type, it can be a boolean. They are about the nicest values out there! There are truthy and falsy booleans, primitive boolean values, and Boolean objects - which aren't really booleans, but can be used in boolean comparisons. Then there are JavaScript expressions, which can also be booleans.

My habit with boolean expressions, was to return the inverse of some variable at the end of a function. As in, initialize a boolean flag (that is, any variable with a boolean value), then invert it's value before returning it. This silly function below, illustrates my point.

    function isOk() {
      var notOk = false;
      // do some logic
      return !notOk;

So the boolean expressions I used involved variables, and I'd somehow trained myself to code this way. This wasn't going to work in my project. I didn't have or want variables to flip in all my functions. Nor was continuing to use keywords like true and false. Lastly, I couldn't continue returning 1's and 0's, since they weren't actual booleans.

Then I recalled that numbers are expressions - they're just missing an operator (or have an implied one, for you uber-geeks). When placing a logical NOT operator before any variable (or, in this case, a number),  the result is a boolean value! Thus, with two characters, I can express the smallest boolean in JavaScript.

    function doAndConfirm() {
      if (doThing())
        return !0;
        return !1;

For some, there are performance implications to consider. I have not tested this, and frankly assume that a computer won't choke on such a minuscule expressions. However, there is a real readability drawback. Plus, I do confuse sending the number 1 instead of "!0".


1 comment:

  1. That is the stupidest thing Ive ever seen.