Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is the ternary operator evaluated in JavaScript?

Regarding the ternary (? :) operator in JavaScript, I would like to know how it is evaluated by a typical browser's JavaScript interpreter:

Alternative A:

  1. Evaluate the first operand.
  2. If the result of the first operand is true, then evaluate and return the second operand.
  3. Else, evaluate and return the third operand.

Alternative B:

  1. All three operands are evaluated.
  2. If the result of the first operand is true, return the result of the second operand.
  3. Else, return the result of the third operand.

Alternative C:

Of course, if neither alternative A nor alternative B accurately describe how the ternary operator works, please explain me how it works.

like image 760
pyon Avatar asked Feb 23 '11 21:02

pyon


1 Answers

According to the specification it works like in Alternative A:

The production ConditionalExpression : LogicalORExpression ? AssignmentExpression : AssignmentExpression is evaluated as follows:

  1. Let lref be the result of evaluating LogicalORExpression.
  2. If ToBoolean(GetValue(lref)) is true, then
    • Let trueRef be the result of evaluating the first AssignmentExpression.
    • Return GetValue(trueRef).
  3. Else
    • Let falseRef be the result of evaluating the second AssignmentExpression.
    • Return GetValue(falseRef).
like image 172
Felix Kling Avatar answered Oct 13 '22 22:10

Felix Kling