Duncan Gravill
Duncan Gravill

Reputation: 4672

'&&' and '||' vs '? :'

Why would you use this syntax?

var myVar = myArray.length && myArray || myObject;

instead of

var myVar = myArray.length ? myArray : myObject;

Edit: I just had a thought that if in the case of the && || syntax both sides of the || evaluated to false, as you might expect if myObject was undefined or null, if false would be returned. But it isn't, the objects value undefined or null is returned.

true  ||  true      //true
true  ||  false     //true
false ||  true      //true
false ||  false     //false

Edit2:

!!(myArray.length ? myArray : myObject);

This does however return false if myObject is undefined or null

Upvotes: 5

Views: 287

Answers (4)

user166390
user166390

Reputation:

x && y || z is different than x ? y : z even if it "works" in the case presented.

Consider when y evaluates to a false-value (in the post y can't be a false-value when it is evaluated because it is dependent upon x and thus it "works" as expected).

Using ?: is the much better and more clear construct in this case. The only reason I can give for using the other syntax is "too much cleverness".

Upvotes: 4

vol7ron
vol7ron

Reputation: 42099

http://jsperf.com/conditional-operators

It looks like you use && || when you want your code to go slower and you want to obfuscate it a little more :)


There's also a difference between what is going on.

foo && bar || foobar  // if foo or bar is false, then foobar will be returned
foo?bar:foobar        // the bar, or foobar, is decided solely on foo

If you wanted the ternary to act like the logical conditional it would be:

foo&&bar?bar:foobar

Upvotes: 1

glglgl
glglgl

Reputation: 91017

A ternary is the only correct thing to do here, unless you guarantee that myObject.name has a "true" value.

Consider

res = a ? b : c;

vs.

res = a && b || c;

What is the difference? The first does what it is supposed to. But the second tests a. If a is false, it gets c, as the ternary version.

But if a is true, it only gets b if this is true as well, if not, it gets c, what is not wanted at all.

Upvotes: 3

Michael Lorton
Michael Lorton

Reputation: 44376

Tastes vary. Maybe somebody just got in the habit of writing things like

var myName = myObject && myObject.name || "unknown";

and stuck with it even when a ternary would work as well.

Upvotes: 1

Related Questions