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);
}
  1. score ← 82

    1void main() {2  var score = 82;3  var grade = score >= 80 ? 'pass' : 'retry';
    values this step82score
  2. score >= 80 ← true, grade ← pass

    2var score = 82;3var grade = score >= 80 ? 'pass' : 'retry';4print(grade);
    values this steptruescore >= 80passgrade82score
  3. print(grade);

    3  var grade = score >= 80 ? 'pass' : 'retry';4  print(grade);5}
    outputpass
    values this steppassgrade

Pick the Grade

  1. score starts at 82.
  2. The check score >= 80 is true.
  3. The ternary chooses pass.
  4. The program prints pass. | Score | Check | Grade | | --- | --- | --- | | 82 | 82 >= 80 is 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