Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript: Conditional (ternary) vs boolean OR for non-boolean values?

Tags:

javascript

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).

like image 997
Ali Shakiba Avatar asked Feb 25 '23 09:02

Ali Shakiba


2 Answers

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 */
like image 55
Delan Azabani Avatar answered Feb 26 '23 23:02

Delan Azabani


ECMAScript language specification, page 83:

The production LogicalORExpression : LogicalORExpression || LogicalANDExpression is evaluated as follows:

  1. Let lref be the result of evaluating LogicalORExpression.
  2. Let lval be GetValue(lref).
  3. If ToBoolean(lval) is true, return lval.
  4. Let rref be the result of evaluating LogicalANDExpression.
  5. 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.

like image 45
Alex Netkachov Avatar answered Feb 26 '23 23:02

Alex Netkachov