A fork in the line
Show on a big screenA rain gauge measures how much rain falls. It read six days: 4, 60, 0, 128, 12, 35 millimetres.
Loading lab…
- A reading arrives: mm = 4.
- Ask: mm ≥ 60? No.
- Ask: mm ≥ 10? No.
- It is a dry day.
Each reading is sorted into a dry, wet or heavy day. Heavy means 60 or more millimetres. Wet means 10 or more, but under 60. Dry means under 10.
The rule
The condition is the yes-or-no question in the round brackets. The block is the lines inside the curly brackets.
An if runs its block only when the condition is true. In this editor, the condition must be true or false. A number or text there stops the run.
if (mm >= 10) { kind = "wet day"; }
Here mm holds one day's reading in millimetres. kind holds the name of the day.
else runs its block when the question above it was false.
| Sign | Asks | Runs to |
|---|---|---|
> | Bigger? | false |
>= | Bigger or same? | true |
< | Smaller? | false |
<= | Smaller or same? | true |
=== | Same? | true |
!== | Different? | false |
Two questions can give three answers. Ask about heavy first, then wet. The else block is for dry.
`` if (mm >= 60) { kind = "heavy day"; } else if (mm >= 10) { kind = "wet day"; } else { kind = "dry day"; } ``
An else if chain stops at the first true question. Swap the questions and every heavy day is called wet. That is because 60 or more is also 10 or more.
Take mm = 128. The first question, 128 >= 60, is true, so the day is heavy. Take mm = 12. The first question, 12 >= 60, is false. The second, 12 >= 10, is true, so the day is wet.
if (mm) { kind = "counted twice"; } is not a question. mm is a number. In this editor, the run stops:
A condition has to be true or false, but this one is a number.
Try the lab to finish this lesson.