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.
var price = 65.00;
var result = price > 50.00 ? "price too high" : "price good value";
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.
var order = 99.00;
var total = order >= 100.00 ? order : order + 10.00;
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.
if(order >= 100.00)
total = order;
total = order + 10.00;
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 Java Script window.open Method
• Include a Quote Character in a String
• Java Script prompt Message Box
• Format a Number as Currency
• Generating Random Numbers
• Java Script Math.sin Method
• Java Script Trigonometric Methods
• The Location Object