How is the ternary operator evaluated in JavaScript?

瘦欲@ 提交于 2019-12-21 07:22:58

问题


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.


回答1:


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");
}



回答2:


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



回答3:


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



回答4:


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


来源:https://stackoverflow.com/questions/5097346/how-is-the-ternary-operator-evaluated-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!