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

6

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.

Basham answered 19/2, 2011 at 5:9 Comment(3)
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.Situation
Related Does JavaScript have short-circuit evaluation?Grodin
For details (especially how it works with truthy/falsy objects), consider these examples!Tedi
R
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?

Robinet answered 19/2, 2011 at 5:15 Comment(4)
There's no short circuiting in VBA, which I learned the hard way after 4 hours of debugging.Cantillate
I've tried to shortcircuit like this with java and it seems the language doesn't allow it. Am I correct?Aquarist
@DarylBennett there is---"AndAlso" and "OrElse". I'd say kill me now, but having no pulse is already a prerequisite for programming VB.Pyxidium
@Aquarist Java definitely has short-circuiting of boolean operators, it just doesn't let you use them as a statement.Strew
J
10

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

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

Jaworski answered 19/2, 2011 at 5:56 Comment(0)
S
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
Stiffen answered 23/1, 2014 at 22:30 Comment(2)
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...Jesu
Be explicit rather than claver and use an if statement...your brain will thank you.Len
O
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...

Overcompensation answered 19/2, 2011 at 5:14 Comment(0)
P
2

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

Payola answered 19/2, 2011 at 5:14 Comment(14)
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"Basham
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]`"Basham
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.Payola
Chap the whole point is that shortcircuiting is to replace if statements - What exactly can an if return other than bool?Payola
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.Basham
@Carno an if statement doesn't return anything. It controls the flow of execution.Basham
Assignment is not occuring but an evaluation of g is happening.Payola
if performs an evalutation upon a condition and RETURNS, ahem, a boolPayola
@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.Basham
"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.Basham
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#.Payola
That's not what I said: it returns a bool for the evalutation of the conditionPayola
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);Payola
@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.Basham
M
-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.

Meshed answered 16/11, 2018 at 10:22 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.