Skip to the workspace
Pebellslearn by building
Control Flow  ›  Lesson

if...else and switch

Control Flow 12 min

javascript / if...else and switch

Explore each scene at your own pace.

01 · if...else and switch

if...else and switch

if...else and switch

if selects code using a condition. An if/else chain takes its first truthy branch. switch selects a starting case using strict equality and then continues until stopped.

A decision chooses which instructions run; later branches do not all run just because their conditions could also be true.

See the mechanism

Walk through the modelif...else and switchAuthored snapshots of the example; use Run below to test the code.
minutes12
12 <= 5false
Skip the first branch and evaluate the next condition.
1 of 3

Follow one example

javascript

For 12, the first test is false and the second is true, so label becomes "medium". The else branch is skipped. Boundary choices such as <= versus < are part of the specification. In switch, use break or return unless fall-through is deliberate; switch does not automatically stop at the next case. In the switch example, the string saved matches its case using strict equality; break ends the switch. An unmatched state reaches default.

Predict, change and check

Predict: At exactly 5 and exactly 15 minutes, which labels should this chain choose?

Test your explanation: Run the example with 5, 6, 15 and 16. Change <= to < in one branch and identify the boundary result you changed.

The tasks below ask you to explain that result and apply the idea to different inputs.

Apply and distinguish

Branches are policies with boundaries

An if condition uses truthiness; it does not require a literal boolean expression. A switch compares the discriminant with case values using strict comparison behavior. A string '1' will not match numeric case 1. Missing break can intentionally or accidentally fall through into later statements.

Test the exact threshold, both sides of it, and the unmatched/default case. Keep zero or empty text valid when the contract allows them. If several cases share one response, group them deliberately and explain the fall-through instead of leaving an accidental dependency on the next case's position.

Check your understanding: State the input contract, identify the operation that changes the result, and give one boundary input that would distinguish the correct rule from the mistake described above.

Scene 1 of 2
Project context and further resources
Additional resources
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.