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:
- Evaluate the first operand.
- If the result of the first operand is true, then evaluate and开发者_StackOverflow社区 return the second operand.
- Else, evaluate and return the third operand.
Alternative B:
- All three operands are evaluated.
- If the result of the first operand is true, return the result of the second operand.
- 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 : AssignmentExpressionis evaluated as follows:
- Let
lrefbe the result of evaluatingLogicalORExpression.- If
ToBoolean(GetValue(lref))istrue, then
- Let
trueRefbe the result of evaluating the firstAssignmentExpression.- Return
GetValue(trueRef).- Else
- Let
falseRefbe the result of evaluating the secondAssignmentExpression.- 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.
- It's inefficient to evaluate all the operands when you are only going to return either the if or the else
- 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())
加载中,请稍侯......
精彩评论