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

Why would you use this syntax?

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

instead

var myVar = myArray.length ? myArray : myObject;

Edit: I just thought that if, in the case of syntax, && ||both sides are ||evaluated as false, as you would expect if you myObjectwere undefinedor nullif false would be returned. But this is not so, the values ​​of the objects undefinedor are returned null.

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

Edit2:

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

However, this returns false if myObjectis undefinedornull

+5
source share
4 answers

x && y || zdiffers from x ? y : z, even if it "works" in the case presented.

, y false ( post y , , x , , "", ).

?: . , , - " ".

+4

- , , , myObject.name "" .

res = a ? b : c;

.

res = a && b || c;

? , . a. a false, c, .

a , b, , , c, .

+3

. , - ,

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

, .

+1

http://jsperf.com/conditional-operators

, && ||, , , :)


, .

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

, , :

foo&&bar?bar:foobar
+1

All Articles