The Conditional Operator
The conditional operator in WMLScript selects between two subexpressions depending on the result of a condition expression. Its syntax is:
condition-expression ? true-expression : false-expression
The condition-expression
is converted to a
Boolean value, and if this results in true
the
result is the true-expression
, and the
false-expression
isn’t evaluated. If
the condition gives Boolean false
or can’t
be converted, the result is the
false-expression
, and the
true-expression
isn’t evaluated.
Neither the true-expression
nor the
false-expression
are converted in any way.
The result of the conditional operator is of the same type as the
selected subexpression.
Note that:
a = b ? c : d;
always has exactly the same effect as:
if (b) { a = c; } else { a = d; }
(Using the conditional operator is usually slightly more efficient
than using if
and else
,
however.)
For example:
true ? "yes" : "no" gives string "yes"
|
false ? "yes" : "no" gives string "no"
|
invalid ? "yes" : "no" gives string "no"
|
true ? 1/2 : 1/0 gives floating-point 0.5
|
false ? 1/2 : 1/0 gives invalid
|
true ? "" : foo( ) gives string "" and doesn’t call foo( )
|
Get Learning WML, and WMLScript now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.