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
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
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'
Java Implementation
String x = (val < 4) ? "hello" : "goodbye";
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)
Made these very easy to understand, thank you Connor!