On this page11 sections
  1. Prerequisites
  2. Learning Objectives
  3. 1. The Shape
  4. 2. Anywhere a Value Fits
  5. 3. Chained Ternaries
  6. 4. Ternary or if-else?
  7. Code Examples
  8. Common Beginner Mistakes
  9. Practice Questions
  10. Practice Answers
  11. Key Takeaways

Lecture 017: The Ternary Operator

Day7: Conditional Expressions & switch
Lecture017 of 057
Estimated video length10 min
TargetDart 3.12
LevelBeginner

Sometimes an if-else exists only to pick one of two values: "adult" or "minor", "item" or "items". The ternary operator condition ? a : b does 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 print and inside ${ }
  • Know when a ternary beats an if-else, and when it doesn't

1. The Shape

code
condition ? valueIfTrue : valueIfFalse
dart
var age = 20;
var status = age >= 18 ? 'adult' : 'minor';
print(status);   // adult

That one line does the same job as:

dart
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.

dart
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.0

3. Chained Ternaries

You can chain them, but it gets hard to read quickly:

dart
var score = 75;
var grade = score >= 80 ? 'A' : score >= 60 ? 'B' : 'C';
print(grade);   // B

For 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 valuesyou're running statements (several lines, prints, updates)
it fits comfortably on one linethe condition or values are long

Code Examples

Example 1: A Shopping Cart Summary

dart
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

code
Hello, guest!
4 items in your cart
Shipping: FREE
Total: Rs 2600

Common Beginner Mistakes

1. Forgetting the : part

dart
var status = age >= 18 ? 'adult';
code
Error: Expected ':' before this.

A ternary always needs both values.

2. Values of different types

dart
String status = age >= 18 ? 'adult' : 0;
code
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

  1. What does 10 > 5 ? 'yes' : 'no' give?
  2. Rewrite as a ternary: if (n % 2 == 0) { kind = 'even'; } else { kind = 'odd'; }
  3. Write a line that prints 1 file or 3 files depending on count.
  4. What's wrong with var x = flag ? 'on';?
  5. Choose: ternary or if-else for printing three lines when a payment succeeds?

Practice Answers

  1. yes
  2. var kind = n % 2 == 0 ? 'even' : 'odd';
  3. print('$count ${count == 1 ? 'file' : 'files'}');
  4. It's missing the : value part.
  5. if-else: it runs statements, not a choice between two values.

Key Takeaways

  • condition ? a : b picks 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-else or switch for anything bigger.