The if statement
- Dart course
- Beginner
- Lesson 36/116
- 4 min
Learn how to check a condition with if.
The if statement
In Dart you check a condition with if. If the condition is true the block runs; if false it is skipped. The form is if (condition) { ... }.
For example int score = 85; if (score >= 50) { print("passed"); } prints passed because score >= 50 is true. The condition goes inside parentheses; the block inside curly braces.
Condition and block
After if a condition is written inside parentheses. The condition must be a bool expression: true or false. Comparison operators (==, !=, <, >, <=, >=) or logical operators (&&, ||, !) produce one.
When the condition is true the block inside the curly braces runs. For single-line blocks the braces are technically optional but always recommended for readability.
Practice Print passed/failed
Declare an int variable score with the value 85. Check the condition with if (score >= 50); when true print print("passed");. The output on a single line must be passed.
Starter code
// Declare score, check 50 and above with if, print passedSample solution
int score = 85;
if (score >= 50) {
print("passed");
}Expected output
passed
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which is a correct if form?
int x = 10;- if (x > 5) print(x);)
- if x > 5 { print(x); }
- if (x > 5) { print(x); } Correct answer
- if [x > 5] { print(x); }
Explanation: The condition goes in parentheses; the block in curly braces.
2 Complete the if condition
int score = 85;
if (____) {
print("passed");
}
int score = 85;
if (score >= 50) {
print("passed");
}
Explanation: score >= 50 is true for 50 and above.
3 Match each part to its job
| Term | Meaning |
|---|---|
if |
Condition statement |
(cond) |
Condition in parens |
{ ... } |
Block |
score >= 50 |
Comparison example |