In JavaScript and Java, the equals operator (==
or ===
) has a higher precedence than the OR operator (||
). Yet both languages (JS, Java) support short-circuiting in if
statements:
When we have if(true || anything())
, anything()
isn't evaluated.
You can also have the following expression: true || foo == getValue())
- for example in an output statement such as console.log(...);
, or in an assignment.
Now, according to operator precedence, short-circuiting shouldn't happen, as ===
= ==
> ||
in terms of precedence. (In other words, the comparison should happen first, for which getValue()
ought to be called, as the equality check has a higher precedence that the OR comparison.) But it does. getValue()
isn't called (as can easily be checked by putting an output statement into its body).
Why (does short circuiting work when the operator precedence says it shouldn't)?
Or am I confusing matters?
getValue()
is not called, but this statement says that is is called. Which is it? – VoletagetValue()
ought to be called..." and his observation that "getValue()
isn't called". – Rompers