Control Flow
If as Expression
Ternary
Dart's ternary cond ? a : b is an expression and produces a value, so it can assign directly into a variable.
Program
Play the program to grade a score in one assignment.
if_expression.dart
Replay: real traced execution (multi-file project)
void main() {
var score = 82;
var grade = score >= 80 ? 'pass' : 'retry';
print(grade);
}
score ← 82
1void main() {2 var score = 82;3 var grade = score >= 80 ? 'pass' : 'retry';values this step82scorescore >= 80 ← true, grade ← pass
2var score = 82;3var grade = score >= 80 ? 'pass' : 'retry';4print(grade);values this steptruescore >= 80passgrade82scoreprint(grade);
3 var grade = score >= 80 ? 'pass' : 'retry';4 print(grade);5}outputpassvalues this steppassgrade
Pick the Grade
scorestarts at82.- The check
score >= 80is true. - The ternary chooses
pass. - The program prints
pass. | Score | Check | Grade | | --- | --- | --- | |82|82 >= 80is true |pass|
ternary
`cond ? a : b` chooses between two values.
expression
Produces a value directly into a binding.
comparison
`>=` returns a `bool`.
Exercise: if_expression.dart
Use a ternary expression to turn score 82 into pass and print the grade