Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 2.4 — switch Statements
JavaScript · Example 2 of 3

Fall-through and strict matching

With no break, case 1 runs on through 2 and 3 until the break. And switch uses ===, so the string "2" never matches the number 2.

switch compares one value against a list of case values with === and jumps to the first match; execution then falls through into the next cases until a break, and default handles no match. For pure value-to-value mapping, an object or Map is often better.

Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.

Ready for more? This phase has 5 hands-on exercises with automatic checks.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Write a switch that turns a number 1 to 3 into gold, silver, bronze, and anything else into no medal. Print the result for 2 and 7.

02

Rewrite the medal mapping as a lookup with a fallback, so there is no switch at all.

Explain it without notes

01

How does switch decide which case matches?

02

What is fall-through, and when is it useful?

03

When would you use an object or Map instead of a switch?

04

Why can declaring let inside a case cause an error, and how do you fix it?

Fall-through and strict matching

Console

(nothing was printed)

Expected console output

bronze
silver
gold
no match: '2' !== 2