David Ly
David Ly

Reputation: 31596

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.

Upvotes: 29

Views: 10343

Answers (6)

Kyle Falconer
Kyle Falconer

Reputation: 8500

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

Upvotes: 6

Cheng
Cheng

Reputation: 84

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.

Upvotes: -1

sdleihssirhc
sdleihssirhc

Reputation: 42496

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

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

Upvotes: 10

Phil Helix
Phil Helix

Reputation: 3733

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

Upvotes: 2

deceze
deceze

Reputation: 522271

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?

Upvotes: 19

Dan Breslau
Dan Breslau

Reputation: 11522

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...

Upvotes: 4

Related Questions