How is the ternary operator evaluated in JavaScript?

前端 未结 4 1040
猫巷女王i
猫巷女王i 2021-02-19 06:19

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

Alternative A:<

相关标签:
4条回答
  • 2021-02-19 06:23

    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).
    0 讨论(0)
  • 2021-02-19 06:23

    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
    0 讨论(0)
  • 2021-02-19 06:28

    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 讨论(0)
  • 2021-02-19 06:49

    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");
    }
    
    0 讨论(0)
提交回复
热议问题