Prajwal Tuladhar’s Blog
 
programming, life and some random thoughts

Archive for May 3rd, 2008

May 03 2008

I am loving ternary operators

Basically ternary operators takes three arguments and sometimes referred as ‘tertiary operator’. At first I don’t know why but I did feel hesitation to use ternary operators as at first it looks petty difficult to understand. Some of my coding friends also rarely use it and may be I got influenced from them. But as I explore coding standards and general patterns of big techies like Google and Yahoo!, I found they use maximum use of ternary operators. Especially in Javascript it does make sense because using them can save your time and size of your code. General syntax for ternary operators in C based languages and its predecessors like like C, C++, Java, C#, PHP, Javascript etc. is like this:

<strong>Condition ? Expression1 : Expression2</strong>

Ternary Operator in Javascript

<span class="kwrd">var</span> flag = <span class="kwrd">true</span>;
alert((flag) ? <span class="str">"Flag is set"</span> : <span class="str">"Flag is not set"</span>);
<a href="http://prajwal-tuladhar.net.np/wp-content/uploads/2008/05/javascript-alert.jpg"><img style="border-right: 0px; border-top: 0px; border-left: 0px; border-bottom: 0px" border="0" alt="javascript_alert" src="http://prajwal-tuladhar.net.np/wp-content/uploads/2008/05/javascript-alert-thumb.jpg" width="405" height="175"></a> 
&nbsp;

Ternary Operator in C#

<span class="kwrd">int</span> flag = 4;
Console.WriteLine((flag &gt;= 5) ? <span class="str">"Flag is more than 4"</span> : <span class="str">"Flag is less 5"</span>);
&nbsp;

console_ternary


Comments

RSS Feed
Subscribe by email
Follow me @ Twitter