Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 411
Davy8 Avatar asked Feb 19 '11 05:02

Davy8


People also ask

What is the synonym of using?

The words employ and utilize are common synonyms of use. While all three words mean "to put into service especially to attain an end," use implies availing oneself of something as a means or instrument to an end. willing to use any means to achieve her ends.

What is the verb of using?

verb (used with object), used, us·ing. to employ for some purpose; put into service; make use of: to use a knife. to avail oneself of; apply to one's own purposes: to use the facilities. to expend or consume in use: We have used the money provided.

What is the act of using something?

noun. the act of employing, using, or putting into service: the use of tools. the state of being employed or used. an instance or way of employing or using something: proper use of the tool; the painter's use of color. a way of being employed or used; a purpose for which something is used: He was of temporary use.

What does use use mean?

1 : to put into action or service : avail oneself of : employ. 2 : to expend or consume by putting to use —often used with up. 3 : stand sense 1d the house could use a coat of paint. 4 : to consume or take (liquor, drugs, etc.) regularly.


2 Answers

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?

like image 71
deceze Avatar answered Sep 21 '22 00:09

deceze


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

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

like image 34
sdleihssirhc Avatar answered Sep 22 '22 00:09

sdleihssirhc