Regarding the ternary (? :
) operator in JavaScript, I would like to know how it is evaluated by a typical browser\'s JavaScript interpreter:
Alternative A:<
According to the specification it works like in Alternative A:
The production
ConditionalExpression : LogicalORExpression ? AssignmentExpression : AssignmentExpression
is evaluated as follows:
- Let
lref
be the result of evaluatingLogicalORExpression
.- If
ToBoolean(GetValue(lref))
istrue
, then
- Let
trueRef
be the result of evaluating the firstAssignmentExpression
.- Return
GetValue(trueRef)
.- Else
- Let
falseRef
be the result of evaluating the secondAssignmentExpression
.- Return
GetValue(falseRef)
.
The ternary operator evaluates lazily for several reasons.
x != 0 ? 10 / x : 10;
If it evaluated everything at the same time you would get a divide by zero error if x were zeroRun 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())
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");
}