Conditional (ternary) operator
You’ve met if statements. Conditional operators (often referred to as ternay operators
work similarly to if-else
statements.
What is a ternary
operator?
A ternary operator
is basically an if-else
statement with more concise
syntax.
Here’s the basic stucture:
What’s happening
If the condition
is true, it will run the trueExpression
(between ?
and :
). If the condition
is false
, it will run the falseExpression
(to the right of :
).
Now a concrete example:
Let’s compare ternary and if-else:
The nice thing with ternary operators is that you can assign the result of the statement to a variable in a concise manner.
Downsides
I generally only use ternary operators
for very simple conditionals. For
anything more complicated I use if-else
statements.