Using && short-circuiting as an if statement?

I saw this line in 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 it is ugly or elegant.

I am not a Javascript guru by any means, so my question is 2 times. First, I want to confirm that I understand correctly. Is the above line equivalent:

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

And secondly, is this common / accepted practice in Javascript? On the one hand, it is brief, but on the other hand, it can be a little mysterious if you have not seen it before.

+28
javascript short-circuiting
Feb 19 '11 at 5:09
source share
6 answers

Yes, your two examples are equivalent. It works something like this in all languages, but in Javascript it gets pretty idiomatic. Personally, I think this is good in some situations, but in others you can abuse it. This is definitely shorter though, which may be important to minimize Javascript load times.

Also see Can anyone explain how John Resig's JavaScript JavaScript works?

+18
Feb 19 '11 at 5:15
source share

It's standard, but JSLint and JSHint like it:

A function assignment or call was expected, and instead saw an expression.

+11
Feb 19 2018-11-11T00:
source share

You have to be careful because this short circuit can be bypassed if there is || in conditional:

 false && true || true > true 

To avoid this, be sure to group conditional expressions:

 false && (true || true) > false 
+7
Jan 23 '14 at 22:30
source share

Yes, you understand this (in this context); Yes, this is standard practice in JavaScript.

+2
Feb 19 '11 at 5:14
source share

Yes, this is equivalent to if , as you wrote. This, of course, is not an unusual practice. Whether it accepts depends on who (or not) makes the reception ...

+2
Feb 19 '11 at 5:14
source share

By default, this will trigger a jshint warning:

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

However, I personally prefer the short-circuit version, it looks more declarative and has "less control logic" , although this may be an erroneous representation.

0
Nov 16 '18 at 10:22
source share



All Articles