What is the Ternary Operator?
The ternary operator is a one-line shorthand for simple if-else statements. It is called "ternary" because it takes three operands: condition, true-value, and false-value.
Syntax
condition ? valueIfTrue : valueIfFalse
Example
void main() {
int age = 20;
String status = age >= 18 ? 'Adult' : 'Minor';
print(status); // Adult
double price = 100.0;
bool isMember = true;
double finalPrice = isMember ? price * 0.9 : price;
print('Final price: \$$${finalPrice.toStringAsFixed(2)}'); // $90.00
int x = 5;
print(x % 2 == 0 ? 'Even' : 'Odd'); // Odd
// In string interpolation
bool isDarkMode = false;
String theme = isDarkMode ? 'dark' : 'light';
print('Theme: $theme'); // Theme: light
}
Output:Adult
Final price: $90.00
Odd
Theme: light
Nested Ternary
You can nest ternary operators, but use sparingly — it hurts readability:
int score = 75;
String grade = score >= 90 ? 'A'
: score >= 80 ? 'B'
: score >= 70 ? 'C'
: 'F';
print(grade); // C
⚠️ Common Mistakes
- Using ternary for multi-line logic — use
if-else instead.
- Over-nesting ternary operators, making code unreadable.
🧠 Quiz
1. What does 5 > 3 ? 'yes' : 'no' return?
- A) 'no'
- B) 'yes' ✅
- C) true
- D) Error
Summary
The ternary operator condition ? trueValue : falseValue is a concise one-line if-else for simple conditions. Use it when both branches return a value. Avoid nesting more than two levels — use if-else if for complex logic instead.