On this page11 sections
Lecture 017: The Ternary Operator
| Day | 7: Conditional Expressions & switch |
| Lecture | 017 of 057 |
| Estimated video length | 10 min |
| Target | Dart 3.12 |
| Level | Beginner |
Sometimes an
if-elseexists only to pick one of two values: "adult" or "minor", "item" or "items". The ternary operatorcondition ? a : bdoes that in a single line, right where the value is needed.
Contents
Prerequisites · Objectives · Lesson · Code Examples · Common Mistakes · Practice Questions · Answers · Takeaways
Prerequisites
Lectures 015–016 (operators and if statements) and 009 (string interpolation).
Learning Objectives
- Write
condition ? valueIfTrue : valueIfFalse - Use it in a variable, a
printand inside${ } - Know when a ternary beats an
if-else, and when it doesn't
1. The Shape
condition ? valueIfTrue : valueIfFalsevar age = 20;
var status = age >= 18 ? 'adult' : 'minor';
print(status); // adultThat one line does the same job as:
String status;
if (age >= 18) {
status = 'adult';
} else {
status = 'minor';
}"Ternary" means "three parts": the condition, the ? value and the : value.
2. Anywhere a Value Fits
A ternary is an expression: it produces a value, so you can use it anywhere a value goes.
var marks = 42;
print(marks >= 50 ? 'Pass' : 'Fail'); // Fail
var count = 1;
print('You have $count ${count == 1 ? 'message' : 'messages'}');
// You have 1 message
count = 3;
print('You have $count ${count == 1 ? 'message' : 'messages'}');
// You have 3 messages
var a = 8, b = 13;
var bigger = a > b ? a : b;
print(bigger); // 13
var isMember = true;
var price = 1000;
print(isMember ? price * 0.9 : price); // 900.03. Chained Ternaries
You can chain them, but it gets hard to read quickly:
var score = 75;
var grade = score >= 80 ? 'A' : score >= 60 ? 'B' : 'C';
print(grade); // BFor more than two choices, an else-if ladder (Lecture 016) or a switch (Lecture 019) is
usually clearer.
4. Ternary or if-else?
| Use a ternary when… | Use if-else when… |
|---|---|
| you're choosing between two values | you're running statements (several lines, prints, updates) |
| it fits comfortably on one line | the condition or values are long |
Code Examples
Example 1: A Shopping Cart Summary
void main() {
var itemsInCart = 4;
var cartTotal = 2600;
var isLoggedIn = false;
var shipping = cartTotal >= 2000 ? 0 : 150;
var label = itemsInCart == 1 ? 'item' : 'items';
var greeting = isLoggedIn ? 'Welcome back!' : 'Hello, guest!';
print(greeting);
print('$itemsInCart $label in your cart');
print('Shipping: ${shipping == 0 ? 'FREE' : 'Rs $shipping'}');
print('Total: Rs ${cartTotal + shipping}');
}Output
Hello, guest!
4 items in your cart
Shipping: FREE
Total: Rs 2600Common Beginner Mistakes
1. Forgetting the : part
var status = age >= 18 ? 'adult';Error: Expected ':' before this.A ternary always needs both values.
2. Values of different types
String status = age >= 18 ? 'adult' : 0;Error: A value of type 'Object' can't be assigned to a variable of type 'String'.One side is a String and the other an int, so the result could be either. Make both sides
the same type.
3. Using a ternary to run statements: isLoggedIn ? print('Hi') : print('Bye'); works, but
an if-else says it more clearly. Ternaries are for choosing values.
4. Long chains: a ? b : c ? d : e ? f : g is hard to read. Use a ladder or switch.
Practice Questions
- What does
10 > 5 ? 'yes' : 'no'give? - Rewrite as a ternary:
if (n % 2 == 0) { kind = 'even'; } else { kind = 'odd'; } - Write a line that prints
1 fileor3 filesdepending oncount. - What's wrong with
var x = flag ? 'on';? - Choose: ternary or if-else for printing three lines when a payment succeeds?
Practice Answers
yesvar kind = n % 2 == 0 ? 'even' : 'odd';print('$count ${count == 1 ? 'file' : 'files'}');- It's missing the
: valuepart. if-else: it runs statements, not a choice between two values.
Key Takeaways
condition ? a : bpicks one of two values.- It's an expression, usable in variables,
print,${ }and arguments. - Both sides should have the same type.
- Use it for short two-way choices; use
if-elseorswitchfor anything bigger.