DEV Community

Cover image for Ternary Operators in under 200 words!
Connor Van Etten
Connor Van Etten

Posted on

Ternary Operators in under 200 words!

Have you ever wanted to write an if-else statement in one line?
Welcome to Ternary Operators! The basic format of a Ternary Operator follows the pseudo code below :

(conditional) ? true-value : false-value
Enter fullscreen mode Exit fullscreen mode

This simple concept allows a user to pass a conditional and replace that line of code with either the true or false value. This can either return a function or even a value if needed.
For example :

x = (conditional) ? true-value : false-value
Enter fullscreen mode Exit fullscreen mode

This will set the value of x to either the true value if the conditional is true and vice versa if the conditional is false.

In each language, ternary operators have slightly different syntax in relation to the ? and : but let's review what the syntax looks like in both Python and Java below:

Python Implementation

x = 'hello' if val < 4 else 'goodbye'
Enter fullscreen mode Exit fullscreen mode

Java Implementation

String x = (val < 4) ? "hello" : "goodbye";
Enter fullscreen mode Exit fullscreen mode

Now go out there and start using Ternary Operators where you see fit! If you are unaware whether your language of choice uses them, please check out this list!

Top comments (1)

Collapse
 
zavier_romano_b8e7e0f003c profile image
Zavier Romano

Made these very easy to understand, thank you Connor!