The Ternary Operation (:?)
<p>So far, we've seen how, in certain contexts, a <a href="/courses/video/9/70/Switch.html">switch construct</a> can be used as a convenient shorthand for <a href="/courses/video/8/64/else.html">if-else constructs</a>. we'll now look at a special operator that works with basic types of the language, which takes this short-hand business one step further. This is the <b>ternary operator, ?:</b> . It can be used for two-choice if-else constructs. For example, if we had the following piece of code using an <a href="/courses/video/8/64/else.html">if-else construct</a>, our sequence of writing shorthand code would see the following progression:</p> <p><i>var max:int = 0; </i></p> <p><i>var a:int = … ; </i></p> <p><i>var b:int = … ; </i></p> <p>// FIRST: coded using the if-else</p> <p><i>if(a > b){ </i></p> <p><i>max = a; </i></p> <p><i>}else{</i></p> <p><i>max = b; </i></p> <p><i>}</i></p> <p><i>trace(max); </i></p> <p>// OR coded using the ternary operator</p> <p><i>max = a>b ? a : b; </i></p> <p><i>trace(max);</i></p> <p>Note that the variable type of 'max' on the LHS (Left-hand side) must match with the variable types 'a' and 'b' on the RHS (Right-hand side.) The general semantics of the usage of the ternary operator is as follows:</p> <p><b><result> = <IF this condition is true> ? <THEN this-outcome> : <ELSE this-outcome>;</b></p> <p>// what follows the ? is the result if the <a href="/course/basics/conditionals-if">condition</a> is <b>true</b>. If the condition is <b>false</b>, what follows the : is the result. Looks complex: is very simple if you read it like an 'if' statement: IF condition true ? (THIS-outcome) : (ELSE this outcome.)</p> <p>As a further note, the expression on the RHS always returns a value of some type, so it can be used as an expression in statements, including function calls. So, the code in part 'b' in the example above can be optimized as:</p> <p><i>trace( a>b ? a : b);</i></p> <p>We have reduced the code clutter by a great deal (actually, we have eliminated the need for declaring and using the <a href="/courses/video/5/157/Using-Variables.html">variable</a> 'max' completely. If you notice, we were simply outputting the value stored in max to the user interface, not performing any other computation with it.)</p> <p>So, the bottom line is this: if you are dealing with 2-way decisions, and are merely using built-in types in logical expressions in <a href="/course/basics/conditionals-if">conditionals</a>, then opt for the ternary operator. It might look a wee bit unwieldy in the beginning, but as you get familiar with it (as any prolific programmer would,) you will understand the importance of brevity in code. If you remember , we had stressed the need and value for readable and well structured code in non-trivial software projects. You now see how well the ternary operator works for both readability and well-structured code.</p>