Using &&'s short-circuiting as an if statement?

Davy8 picture Davy8 · Feb 19, 2011 · Viewed 8.9k times · Source

I saw this line in the jQuery.form.js source code:

g && $.event.trigger("ajaxComplete", [xhr, s]);

My first thought was wtf??

My next thought was, I can't decide if that's ugly or elegant.

I'm not a Javascript guru by any means so my question is 2-fold. First I want to confirm I understand it properly. Is the above line equivalent to:

if (g) {
    $.event.trigger("ajaxComplete", [xhr, s]);
}

And secondly is this common / accepted practice in Javascript? On the one hand it's succinct, but on the other it can be a bit cryptic if you haven't seen it before.

Answer

deceze picture deceze · Feb 19, 2011

Yes, your two examples are equivalent. It works like this in pretty much all languages, but it's become rather idiomatic in Javascript. Personally I think it's good in some situations but can be abused in others. It's definitely shorter though, which can be important to minimize Javascript load times.

Also see Can somebody explain how John Resig's pretty.js JavaScript works?