Possible Duplicate:
JavaScript: Is “z=(x||y)” same as “z=x?x:y” for non-boolean?
Are the following two lines of code equivalent in javascript?
a = b ? b : c
a = b || c
I want to express: “a should be assigned b if b is truthy, otherwise a should be assigned c”
I expect they would both work exactly the same, but I’m not 100% sure.
Yes. The two are almost exactly identical.
Both will first evaluate
b. If it’s truthy, it’ll returnb. Else, it’ll returnc.As pointed out by @thesystem, if you have a getter method on
b, it’ll be called twice for the ternary, but only once for the or statement.Test it using the following snippet:
Here’s the fiddle: http://jsfiddle.net/bqsey/