Using &&'s short-circuiting as an if statement?
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.
Solution 1:
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?
Solution 2:
It's standard, but neither JSLint nor JSHint like it:
Expected an assignment or function call and instead saw an expression.
Solution 3:
You must be careful because this short-circuiting can be bypassed if there is an ||
in the conditional:
false && true || true
> true
To avoid this, be sure to group the conditionals:
false && (true || true)
> false
Solution 4:
Yes, it's equivalent to an if
as you wrote. It's certainly not an uncommon practice. Whether it's accepted depends on who is (or isn't) doing the accepting...