Ternary Operator Tutorial Examples – Ruby, JavaScript and VB

Fork-in-the-RoadMy favorite snippet of programming code is the ternary operator used to handle a Boolean evaluation (true/false). It is concise no matter which language Ruby, JavaScript or VB.net.

Anatomy of the Ternary operator:
A ternary is a two-step conditional method; evaluate and execute. The evaluation must be conditional Boolean, that is it must ask for true false results. Think of it like a turnstile or a fork in a road where it will either be open or closed. There is no third option as with If/Then/Else. But the beauty of the ternary is not in extensibility but rather brevity. The ternary is concise and keeps code tight and short. Consider the following JavaScript If/Else statement that sets a discount of 10% only if the age variable is greater than or equal to 65.

if(age>=65){
 discount = total * '.10';
 }
 else{
 discount = '0';
 }

Now look at the Ternary version:

discount=(age>=65)? total * '.10' : '0' ;

Here’s the syntax in JavaSctipt, Ruby and VB:

Ruby Ternary Operator:
 (condition) ? (result if the condition is true) : (result if the condition is false)

discount=(age>=65) ? total * '.10' : '0'
VB.NET 2008 Ternary Operator:
 If((Condition), (result if the condition is true), (result if the condition is false)) 

discount = If(age>=65, total; * '.10', '0')
VB 6.0 and up Ternary Operator:
 IIf((Condition), (result if the condition is true), (result if the condition is false))

discount = IIf(age>=65, total; * '.10', '0')
JavaScript Ternary Operator (AKA Conditional Operator):
 (condition) ? value1 : value2 ;

discount=(age>=65)? total * '.10' : '0' ;

Try a client side JavaScript version yourself:

Are you eligible for a senior discount?

How old are you?

Total: 250

Discount: 250

Balance:

You can also copy/paste the code below into a text editor and save as and html document. Browse the document with I.E, Firefox or Chrome and you’ll get a working example.

<!DOCTYPE html>
<html>
<body>
<p>Are you eligible for a senior discount?</p>
How old are you? <input id="age" value="65" />
<button onclick="seniorDiscount()">Check for discount</button>
<p>Total: 250</br>
Discount: <span id="discountme">250</span></br>
Balance: <span id="totalme"></span>
</p>
</div>
<script>function seniorDiscount(){var total,age,discount;total='250';age=document.getElementById("age").value;discount=(age>=65)? total * '.10' : '0';total -= discount;document.getElementById("discountme").innerHTML=discount;document.getElementById("totalme").innerHTML=total;}</script>
</body>
</html>

Leave a Reply

Your email address will not be published. Required fields are marked *

*