Ternary
- Dart course
- Beginner
- Lesson 40/116
- 4 min
Learn to write a conditional expression in one line with ? :.
Ternary
The ternary is a short way to write a conditional expression on one line: condition ? valueA : valueB. If the condition is true valueA is produced; if false valueB. The result can be assigned to a variable or printed directly.
For example var label = n >= 0 ? "positive" : "negative"; picks a label based on the sign of n. The ternary is the short form of if/else for simple two-way choices; avoid very complex ternaries for readability.
Ternary and if/else
The ternary is an expression; it produces a value and can be assigned to a variable. if/else is a statement; it runs a block but produces no value. They serve different needs.
For simple two-way assignments the ternary is shorter: var s = x > 0 ? "pos" : "neg";. But for complex branching with side effects (print, assignment) if/else is more readable. Practical tip: use the ternary only to pick a value; leave side effects to if/else.
Practice Even/odd label
Declare an int variable n with the value 8. Declare a variable label and assign the ternary n % 2 == 0 ? "even" : "odd" to it. Then print label with print(label);. The output on a single line must be even.
Starter code
// Declare n, assign even/odd label with ternary, print itSample solution
int n = 8;
var label = n % 2 == 0 ? "even" : "odd";
print(label);Expected output
even
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Complete the ternary
int n = 7;
var label = n % 2 == 0 ____ "even" : "odd";
print(label);
int n = 7;
var label = n % 2 == 0 ? "even" : "odd";
print(label);
Explanation: The ? separates the condition from the true value.
2 Match each part to its job
| Term | Meaning |
|---|---|
cond ? |
Condition and true arm |
: valueB |
False arm |
if/else |
Two-way statement |
ternary |
Two-way expression |
3 What is the output of this code?
int n = 7;
print(n % 2 == 0 ? "even" : "odd");- true
- even
- odd Correct answer
- 0
Explanation: 7 % 2 == 0 is false, so 'odd' is produced.