LA.NET [EN]

Sep 15

In one of my latests posts on JavaScript, I’ve tried to present a technique known as boolean normalization. The idea is to use the ! operator twice in order to convert any value to a boolean. At the time, instead of relying in a simple expression (ex.: var t = !! something), I’ve opted for writing the following function:

function doSomething(isTrue) {
    if (!!isTrue) {
        //some code here
    }
}

I probably wasn’t clear enough about this snippet: I’ve only written it for *illustrative* purposes. Yes, the !! operator isn’t really needed there because we can simply rely on the “interpretation” of truthy and falsy values in JavaScript. On the other hand, it’s also true that using the !! isn’t really causing any harm (in my opinion, it’s only pointless in this simple case).

It happens that the post was interpreted by some as a recommendation, ie, as a good usage of the !! pattern. Some thought the code was so bad, that it deserved its own entry on the Daily WTF.

I must confess that when I’ve written that snippet I wasn’t expecting so much fuss around it. After all, it was only intended to illustrate one way to convert any expression to a boolean. Since I don’t want anyone who reads this blog and is starting with JS to think that there really isn’t any “real” world usage for this pattern, I’ve decided to write a follow up on this topic.

The first thing you need to understand (if you still haven’t,that is) is that using the !! pattern will always yield a boolean,ie, you’ll always get true or false (instead of the original expression). There are some scenarios where you really need a boolean and not an expression.  For instance, the next example shows a function which converts any expression into a boolean (btw, I really don’t have lots of time for writing samples, so I’m assuming that people will not nominate the snippet for WTF based on my the names of the functions :) ):

function isTheParameterValid(par) {
    return !!par;
}

Notice that isTheParameterValid will always convert par into a boolean (it will check for falsy values during the first ! operator execution and the second will convert it back to its “initial boolean value”). If you look at modern JS language libraries, you’ll see that this technique is used whenever the use of a “true” boolean is required. You should keep in mind that both ifs in the next snippet produce the same result:

var t = "something";
if( t ){...
if( isTheParameterValid(t) ){ ...

The difference is that the first is relying on JS evaluation of expressions (based on JS definition of falsy values) and the second is using a "real” boolean. This might be an important difference when you have several conditions, but I’ll leave that for a future post.

I couldn’t really end up this post without looking at the code of some of the existing JS libraries and searching explicitly for the !! usage. And yes, most of its usage falls in one of the scenarios I’ve mentioned before (it will be used for setting a variable to true or false, to return a boolean from a function and when you use the logical &&/|| operators). The surprise was that even JQuery has code which is similar to the one I presented in the previous snippet, ie, it has a simple if with one condition and it uses the !! pattern. Here’s the “guilty" line:

if ( !!document.getElementById( id ) ) {
  Expr.find.ID = function(match, context, isXML){

Interesting, wouldn’t you say? JQuery has a WTF if on it (a least, according to these guys)…

I hope this post makes things perfectly clear regarding the !! pattern. Stay tuned for more on JavaScript.

3 comments so far

  1. Bertrand Le Roy
    7:19 pm - 9-15-2009

    Sure in many cases it”s not strictly useful, in the same way that in most cases, == is alright but we prefer to use === because it”s more predictable. It makes the code easier to manage and it prevents some tricky bugs. It”s coding hygiene.
    But here”s a case where it really is useful:
    var isBar = !!someMutableObject.bar;
    // do stuff that might mutate the objet and its bar.
    if (isBar) <- still true
    if (omeMutableObject.bar) <- who knows?

  2. Jonathan Allen
    8:33 pm - 9-15-2009

    My appologies. When I said it should be a DailyWTF entry, I was refering to to state of JavaScript itself. I didn”t mean to suggest your code was wrong.

  3. luisabreu
    9:21 pm - 9-15-2009

    To be honest, there”s really nothing to apologize. I enjoy good discussions related to programming (when I started blogging, the idea was to introduce several topics and discuss them through comments and other posts).

    I”ve only added this entry to clear any misunderstandings that might have arose with the previous post.

Leave a Reply

Your email address will not be published. Required fields are marked *


*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>