The Conditional Operator
By Stephen Bucaro
The Java Script Conditional Operator uses a question mark (?) and a colon (:)
as a short-cut way to create an if⁄else statement.
condition ? expression1 : expression2
If condition evaluates to true, the ? operator returns expression1.
If condition evaluates to false, the ? operator returns expression2.
The example code below might be a test to see if you're paying too much for cable television.
<script type="text/javascript">
var price = 65.00;
var result = price > 50.00 ? "price too high" : "price good value";
alert(result);
</script>
The condition here is price > 50.00. If the price is greater-than 50.00,
the ? operator returns the first string "price too high". If the price is NOT greater-than
50.00, the ? operator returns the second string "price good value".
The example code below might be used to determine shipping charges on an order.
<script type="text/javascript">
var order = 99.00;
var total = order >= 100.00 ? order : order + 10.00;
alert(total);
</script>
The condition here is order >= 100.00. If the order is equal-to or greater-than 100.00,
the ? operator returns the first expression. In other words the shipping is free. If the
order is NOT equal-to or greater-than 100.00, the ? operator returns the second expression,
which adds 10.00 to the total. In this example, the poor fool made an order for just below
where he could have got free shipping.
The conditional statement above could be replaced with the if⁄else
statement shown below.
<script type="text/javascript">
if(order >= 100.00)
{
total = order;
}
else
{
total = order + 10.00;
}
</script>
Some programmers prefer to use the confusing conditional Operator rather than the
simple if⁄else statement either because it uses less code or because they think
they're super-duper programmers. Well, since the if⁄else statement can also
be coded in one line as shown below, I would say the latter is true.
if(order >= 100.00) total = order; else total = order + 10.00;
More Java Script Code: • The Conditional Operator • Interactively Set Webpage Colors • The Java Script window.open Method • JavaScript Operators • JavaScript Character Escape Sequences • Rounding a Number with JavaScript • The Screen Object • The Browsers History Object • Using the Java Script eval() Function • Java Script prompt Message Box
|