HTML and CSS Reference
In-Depth Information
5.2.7 The Conditional Operator
The conditional operator is called a ternary operator because it requires three operands.
It is often used as a shorthand method for if/else conditional statements. (See Chapter 6,
“Under Certain Conditions.”) Although we cover if/else in Chapter 6, the following for-
mat shows both the conditional operator and how it translates to an if/else statement.
FORMAT
conditional expression ? expression : expression
EXAMPLE
x?y:z If x evaluates to true, the value of the expression
becomes y, else the value of the expression becomes z
big = (x > y) ? x : y
If x is greater than y , x is assigned to
variable big , else y is assigned to
variable big
An if/else statement instead of the conditional statement:
if (x > y) {
big = x;
}
else{
big = y;
}
EXAMPLE 5.12
<html>
<head>
<title>Conditional Operator</title>
</head>
<body bgcolor="lightblue">
<big>
<script type ="text/javascript">
1
var age = prompt("How old are you? ", "");
2
var price = (age > 55 ) ? 0 : 7.50;
3
alert("You pay $" + price + 0);
</script>
</big>
</body>
</html>
 
 
Search WWH ::




Custom Search