Adding Ternary Operators to the mix

A ternary operator is an operator that takes three arguments, a condition and two expressions and determines which expression is valid.  It is used like a consolidated if/else conditional operator statement.  I have started to incorporate them a bit more frequently in both JavaScript and C# code to minimize extra lines when expressions are simple and the code is easily readable.

Here’s an example:

"Hello, " + (isMorning ? "Good Morning" : "Good Evening");

The code snippet above evaluates the condition of the boolean ‘isMorning’ to determine which expression should be displayed to the user.  If ‘isMorning’ conditional check is true, the first expression is displayed, otherwise the second condition is displayed.

The syntax is a condition separated by a question mark (*?*) followed by expression 1 (can be interpreted as the if condition), which is separated by a colon(*:*) then followed by expression 2 (which can be interpreted as the else condition).

So a translation from the Ternary Operation to an IF Statement would be:

If (isMorning){
     "Good Morning";
     "Good Evening";



About dalain

Dalain is a Technical Program Manager, entrepreneur and speaker that specializes in Technology for Businesses, STEM, StartUps, and Economic Development. As well as running a business and writing, he spends time volunteering in the community, supporting Black Businesses, listening to underground hip hop, and helping those in need.