In JavaScript, can I always use boolean OR instead of conditional operator for all kind of variables (e.g. string, function, ...)?
For example z = (x || y)
instead of z = (x ? x : y)
.
They are similar, but are not quite the same. x ? x : y
ends up evaluating x
twice if x
is chosen. This could cause an unexpected effect if x
is a function call.
You can find a formal proof of this in the ECMA specification.
Another way to prove this:
function a() { c++; return true; }
function b() { d++; return true; }
var c = 0, d = 0;
a() || 3;
b() ? b() : 3;
/* c is 1; d is 2 */
ECMAScript language specification, page 83:
The production LogicalORExpression : LogicalORExpression || LogicalANDExpression is evaluated as follows:
- Let lref be the result of evaluating LogicalORExpression.
- Let lval be GetValue(lref).
- If ToBoolean(lval) is true, return lval.
- Let rref be the result of evaluating LogicalANDExpression.
- Return GetValue(rref).
So the || returns the value of the variable, not the boolean result of operation. This value is converted to boolean by the if (...)
statement.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With