Pebellslearn by building
0%
RoadmapsMatrixCoursesSandboxSign in
Loops and Control Flow  ›  Lesson

if...else and switch

if...else 12 minif/else if/else tests any boolean condition in order and runs the first true branch; switch compares one value against a list of fixed cases and needs break to stop, or it falls through into the next case.

if...else and switch

In short: if / else if / else tests conditions in order and runs the first one that's true, skipping the rest — any boolean expression is fair game. switch (value) compares one value against a list of fixed cases and jumps straight to the matching one — but it falls through: once it starts running a case's code, it keeps going into the next case too, unless you stop it with break. switch is really if/else sugar for "one value, several fixed options."

Left: if/else if/else as a fork with signposts, each its own true/false test, only one branch taken; right: switch(status) as a rotary dial that lands on exactly one matching case, or default

Tiered shipping fees

if/else if/else handles ranges and arbitrary conditions naturally:

javascript

Each branch is tested in order, top to bottom, and the first true one wins — 2500 > 2000 is true, so the chain stops right there and never even looks at the other conditions. This reads naturally for ranges and combinations that switch can't express directly.

A status code with fixed options

When you're really asking "which one of these exact values is it?", switch is clearer:

javascript

"PACKED" and "SHIPPED" share one return by stacking two case labels — a deliberate, controlled fall-through. default is switch's else: it catches anything that matched no case.

The trap: forgetting break

Stack cases without a return or break, and execution keeps sliding down into the next case's code — often by accident:

javascript

grade(95) should probably just be "A", but with no break after that case, execution falls straight into the score >= 70 case too, giving "A-ish". Every case needs a return or an explicit break unless falling through is exactly what you want.

Quick practice

quick drill

In if (x > 10) { ... } else if (x > 5) { ... } else { ... } with x = 20, which branch runs?

quick drill

What does a switch statement do when a case has no break and no return?

quick drill

What is switch best suited for, compared to if/else?

Practice — level up

0/1 solved

Write your answer, then compare it with a rubric and a model answer.

ExplainThe missing break

A switch statement for order status is missing a break after the "PACKED" case, so a PACKED order prints both the PACKED message and the SHIPPED message. Explain exactly why, using the term fall-through, and how to fix it.