Javascript trernary statement equivilance

Possible duplicate:
JavaScript: Is "z = (x || y)" the same as "z = x? X: y" for non-zero?

Are the following two lines of code equivalent in javascript?

a = b ? b : c a = b || c 

I want to express: "a must be assigned b if b is true, otherwise a must be assigned c"

I expect both of them to work the same way, but I'm not 100% sure.

+4
source share
2 answers

Yes. They are almost exactly identical.

Both will appreciate b first. If he is truthful, he will return b . Otherwise, it will return c .


As pointed out by @thesystem, if you have a getter method on b , it will be called twice for triple, but only once for the or operator.

Test it using the following snippet:

 var o = {}; o.__defineGetter__("b", function() { console.log('ran'); return true; }); var d = ob || o.not; console.log('-----'); var d = ob ? ob : o.not; 

Here's the fiddle: http://jsfiddle.net/bqsey/

+4
source

Logical operators are usually used with logical (logical) values; when they are, they return a boolean value. However, && and || operators actually return the value of one of the specified operands, so if these operators are used with non-zero values, they can return a non-zero value.

ref: Logical operators - MDN

+1
source

All Articles