Eastern Monk
Eastern Monk

Reputation: 6635

Is it a good practice to depend on boolean operators returning one of their operands?

I often rely on the fact that in Javascript conditional operators do not return true or false but one of the arguments.

For example:

function(e){
    this.someotherfunction.apply(this, e.config || []); 
}

So far I have not come across any issues and when I tried to find out what Douglas Crockford (read JSLint) has to say about it, I haven't found any issue.

Are there any dangers in using this kind of syntax?

Upvotes: 2

Views: 49

Answers (4)

epascarello
epascarello

Reputation: 207511

Only issue you may face is an angry developer saying they have a hard time reading it and would demand it to be rewritten as.

foo : function (e) {
    var config =  e.config || [];
    this.someotherfunction.apply(this,config); 
}

And yes, I have run into those angry developers.

Upvotes: 1

Quentin
Quentin

Reputation: 943586

The approach is idiomatic JavaScript.

Are there any dangers in using this kind of syntax?

You do have to be careful about knowing what the inputs are. e.g. if something expects a number, then you have to account for 0 being a false value.

Upvotes: 1

Oleg V. Volkov
Oleg V. Volkov

Reputation: 22421

This is perfectly documented and works that way in many dynamic languages. It is safe to use this construction and it is widely recognized.

Upvotes: 1

gdoron
gdoron

Reputation: 150253

Are there any dangers in using this kind of syntax ?

No.

(As long as you and all other developers know what this code does...)

Upvotes: 3

Related Questions