Consider the task at hand and refer to JavaScript Operator Precedence
var r = data && data.x || 0
The &&
operator takes precedence over the ||
operator. It returns the last operand if both are true, otherwise it returns false. Therefore, the expression simplifies to:
var r = data.x || 0
Now, the ||
operator will return the first truthy operand, in this case, data.x
:
var r = data.x
When it comes to Javascript objects themselves, they always evaluate to true, even if empty (e.g., obj = {}
)
However, when validating an object's property, things change: if the property has a Boolean value of false
or a numeric value of 0
, it will be considered false because 0 == false
but 0 !== false
.
For example:
var data = { x:false, y:456 };
var r = data && data.x || 999;
In this case,
r
would be
999
, just like if
data.x
was set to `0.