29

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.

Davy8
  • 30,868
  • 25
  • 115
  • 173
  • Considering that those braces aren't even required in the second case, I'd vote unclear and ugly, although I am not a JavaScript guru either. – cst1992 Mar 22 '16 at 11:49
  • 1
    Related [Does JavaScript have short-circuit evaluation?](https://stackoverflow.com/questions/12554578/does-javascript-have-short-circuit-evaluation) – Jonas Wilms May 09 '19 at 09:28
  • For details (especially how it works with truthy/falsy objects), consider [these examples](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_AND#examples)! – Cadoiz Mar 29 '23 at 07:18

6 Answers6

19

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?

Community
  • 1
  • 1
deceze
  • 510,633
  • 85
  • 743
  • 889
  • There's no short circuiting in VBA, which I learned the hard way after 4 hours of debugging. – Daryl Bennett Apr 24 '15 at 22:02
  • I've tried to shortcircuit like this with java and it seems the language doesn't allow it. Am I correct? – MaxG May 09 '16 at 22:38
  • 3
    @DarylBennett there is---"AndAlso" and "OrElse". I'd say kill me now, but having no pulse is already a prerequisite for programming VB. – hraban Nov 19 '16 at 19:31
  • @MaxG Java definitely has short-circuiting of boolean operators, it just doesn't let you use them as a statement. – user229044 Apr 12 '19 at 15:09
10

It's standard, but neither JSLint nor JSHint like it:

Expected an assignment or function call and instead saw an expression.

sdleihssirhc
  • 42,000
  • 6
  • 53
  • 67
6

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
Kyle Falconer
  • 8,302
  • 6
  • 48
  • 68
  • 3
    That's because ANDs take precedence on ORs when they're side-by-side. Equivalent maths situation would be `2*3+2 = 8` when `2*(3+2) = 10`. This is way too easy to miss... – Alex May 26 '14 at 15:03
  • Be explicit rather than claver and use an if statement...your brain will thank you. – Daniel Sokolowski Apr 12 '19 at 15:05
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...

Dan Breslau
  • 11,472
  • 2
  • 35
  • 44
2

Yes, you understand it (in that context); yes, it is standard practice in JavaScript.

Phil C
  • 3,687
  • 4
  • 29
  • 51
  • It most certainly is not standard practice in C#. In fact it won't even compile "Only assignment, call, increment, decrement, and new object expressions can be used as a statement" – Davy8 Feb 19 '11 at 05:22
  • And that's only if the 2nd half returns `bool` otherwise you get "&& operator cannot be applied to arguments of type 'bool' and '[whatever type the 2nd half returns]`" – Davy8 Feb 19 '11 at 05:25
  • you need to put it in brackets and assign. Just for you, I'll remove the bit about C# because the question is specifically about JavaScript. – Phil C Feb 19 '11 at 05:26
  • Chap the whole point is that shortcircuiting is to replace if statements - What exactly can an if return other than bool? – Phil C Feb 19 '11 at 05:28
  • The question wasn't about how short-circuiting works though. It's specifically about using a short-circuited boolean operator for the side-effects and not for boolean logic. There is no assignment happening in the sample I gave above. – Davy8 Feb 19 '11 at 05:29
  • @Carno an `if` statement doesn't return anything. It controls the flow of execution. – Davy8 Feb 19 '11 at 05:32
  • Assignment is not occuring but an evaluation of g is happening. – Phil C Feb 19 '11 at 05:32
  • if performs an evalutation upon a condition and RETURNS, ahem, a bool – Phil C Feb 19 '11 at 05:34
  • @Carno I don't disagree that an evaluation of g is happening, but that isn't the question. I'm mostly contesting the earlier statement about C# but maybe I should just drop it since you removed it from your answer. Basically if my example were instead `someBool && alert('hi');` then the C# equivilent would be `someBool && MessageBox.Show("hi");` which won't compile for multiple reasons, you can't && a bool and a void, and also you can't have an && expression then discard the result. – Davy8 Feb 19 '11 at 05:39
  • "if performs an evalutation upon a condition and RETURNS, ahem, a bool" that is just a completely false statement. In a javascript console, do `a = true;` then `if(a) {alert('something')};' the return value of that expression says `undefined` in Firebug. – Davy8 Feb 19 '11 at 05:43
  • Yes, you can only shortcircuit conditions that when evalutated would return bool. The main reason I removed the C# comment is because && has overloaded meanings in JavaScript that C# does not have. One such overloaded meanings (viz., the one is in your question) has no equivalent in C#. – Phil C Feb 19 '11 at 05:48
  • That's not what I said: it returns a bool for the evalutation of the condition – Phil C Feb 19 '11 at 05:55
  • Here is the kind of example I had in mind for C# where if is not used but && is used to evaluate a chain of expressions: return (valueAsString != null && valueAsString.Length >= _minCharacters); – Phil C Feb 19 '11 at 06:08
  • @Carno I understand that, but again that isn't what the question is asking about. If you notice there is neither assignment or a return in my example. What you're describing is just the normal use of a short-circuited `and` operator that's used in most languages. The question is specifically about when you throw away the result of the the && and use it purely for the side-effects. I thought that was clear by just having that alone as a full statement without a return and without doing anything with the result of the && but maybe I should have been more explicit in what I meant. – Davy8 Feb 19 '11 at 14:55
-1

By default, it will trigger a jshint warning:

[jshint] Expected an assignment or function call and instead saw an expression. (W030) [W030]

However personally, I prefer the short-circuit version, it looks more declarative and has "less control logic", might be a misconception though.

Cheng
  • 84
  • 1
  • 4