else and else if
- Dart course
- Beginner
- Lesson 37/116
- 4 min
Learn else and else if chains for alternative cases.
else and else if
To run another block when the if condition is false you use else. In if (cond) { A } else { B } A runs when the condition is true; B when it is false.
To check several conditions in order you build an else if chain: if (a) { ... } else if (b) { ... } else { ... }. Dart checks top to bottom; it runs the first true block and skips the rest.
else if chain
To separate three or more cases you use else if. For example computing a grade: if (score >= 90) { print("A"); } else if (score >= 80) { print("B"); } else { print("C"); }.
Dart checks top to bottom; it runs the first true block and skips the rest of the chain. So putting the strictest condition first is efficient. The else block is optional; if no condition is true it is skipped.
Practice Print the grade letter
Declare an int variable score with the value 75. If score >= 90 print print("A");, else if score >= 70 print print("B");, in the else block print print("C");. The output on a single line must be B.
Starter code
// Declare score, print grade letter with if/else if/elseSample solution
int score = 75;
if (score >= 90) {
print("A");
} else if (score >= 70) {
print("B");
} else {
print("C");
}Expected output
B
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Write the else keyword
int score = 40;
if (score >= 50) {
print("passed");
} ____ {
print("failed");
}
int score = 40;
if (score >= 50) {
print("passed");
} else {
print("failed");
}
Explanation: else runs when the if condition is false.
2 When does the else block run?
if (cond) { A } else { B }- when cond is always true
- when cond is true
- never
- when cond is false Correct answer
Explanation: The else block runs when the if condition is false.
3 Match each part to its job
| Term | Meaning |
|---|---|
if (a) |
First condition |
else if (b) |
Second condition |
else |
If none match |
{ ... } |
Block |