开发者

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开发者_StackOverflow社区 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.


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


The "alternative A":

(1)? functionOne(): functionTwo()

If you put a simple alert message on both functions, only functionOne will display its message.

function functionOne(){ 
   alert("one");
}
function functionTwo(){ 
   alert("two");
}


The ternary operator evaluates lazily for several reasons.

  1. It's inefficient to evaluate all the operands when you are only going to return either the if or the else
  2. Doing lazy evaluation allows you to do things like x != 0 ? 10 / x : 10; If it evaluated everything at the same time you would get a divide by zero error if x were zero


Run this and find out:

function bool() {
    alert('bool');
    return false;
}

function a() {
    alert('a');
    return 'A';
}

function b() {
    alert('b');
    return 'B';
}

alert(bool() ? a() : b())
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜