- 3.4 Ternary Operator
- What Is a "Ternary Operator"?
- Why Use a Ternary Operator?
- Basic Structure
- Previous Section
- Next Section
3.4 Ternary Operator
What Is a "Ternary Operator"?
? in its structure, and assigns a value to a variable based on some condition. This is like a shorter form of a
Why Use a Ternary Operator?
It's simply syntax sugar (something that makes your code more pretty). You can replace a ternary operator with an
Here is the basic structure:
<condition> ? <value1> : <value2>;
- Ternary operator starts with conditional expression followed by the
- The second part (after
:operator) will be placed into the variable if the condition is true.
- IF the condition is false, then the third part (after
:) will be placed into the variable.
You can add practice problems here if you want. Follow the format below.