17

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.

4
  • 4
    The "alternative A": (1)? functionOne(): functionTwo(), if you put a simple alert message on both functions, only functionOne will display its message. Commented Feb 23, 2011 at 21:27
  • Oh, wow. Thanks. Post it as an answer so I can accept it. Commented Feb 23, 2011 at 21:28
  • 1
    You could test this faster than someone replies. Commented Feb 23, 2011 at 21:28
  • I cannot test it on IE6, IE7 and IE8. Commented Feb 23, 2011 at 21:29

4 Answers 4

11

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");
}
Sign up to request clarification or add additional context in comments.

Comments

11

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

Comments

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

1 Comment

Sorry, random correction: No division by zero error in JS. 1/0 === Infinity
2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.