JavaScript lesson · 18 min
JavaScript switch Statement
Choose one branch from several named cases with switch, case, break, and default.
What you will practice
- Use switch for one value with many possible cases.
- Understand why break matters.
- Add a default fallback branch.
What this means
A `switch` statement compares one value against several possible cases.
It is useful when you have one clear value, such as a status, role, command, or category, and each value needs a different result.
`break` stops JavaScript from continuing into the next case. `default` handles values that do not match any listed case.
If this is your first time seeing this
A switch is a neat way to choose between many exact values.
It is usually easier to read than a long chain of `else if` statements when every branch checks the same variable.
Mini glossary
- switch
- A statement that compares one value against multiple cases.
- case
- One possible matching value inside a switch.
- default
- The fallback branch when no case matches.
Example from everyday life
A switch statement is like choosing a counter at an airport. If your ticket says departures, go to one counter. If it says baggage, go to another. If the label is unknown, go to the help desk.
How it works step by step
- The code starts with a status value: `review`.
- The switch checks the status against each case.
- When it reaches `case "review"`, it sets a message and stops with `break`.
- If none of the cases matched, the default branch would create a fallback message.
Where you will use this
- A UI chooses a badge color from a status string.
- A role system chooses permissions for admin, editor, and viewer.
- A command parser chooses what action to run from a command name.
Before you run the code
Use switch when one value has several exact named possibilities.
Use if/else when conditions are more complex than exact cases.
Common beginner mistakes
- Forgetting `break` and accidentally running the next case too.
- Using switch for complex conditions where if/else would be clearer.
- Forgetting a default branch.
Run the code to see console output here.
Code runs locally in a temporary browser worker with a timeout. It is not sent to Lumio analytics or executed on the server.
Try changing this next
- Change status to `published`.
- Change status to `archived` and watch the default branch.
- Remove a `break` and see why it matters.