Programming Basics
Ternary & Switch (Multi-Way Choice)
The idea, in plain English
A ternary is a tiny if/else squeezed onto one line. It's a shortcut fork in the road for when you only have two paths and a quick question to pick between them, like 'old enough? then adult, else minor'. A switch is for when you have MANY paths branching from one value, like a vending machine: press button 1 for chips, button 2 for soda, button 3 for candy — and if nothing matches, a default slot.
How it works
- 1A ternary has the shape `condition ? valueIfTrue : valueIfFalse`. It's an expression, so it hands back a value directly instead of needing a full if/else block.
- 2A switch checks one value against a list of `case`s, one after another, and runs the code under whichever `case` matches. A `break` afterward stops it from falling into the next case by accident.
- 3If none of the cases match, a `default` case, or the language's equivalent, catches everything else, just like the final `else` in an if/else chain.
When you'd use it
Reach for a ternary when you're picking between exactly two short values, like choosing a label or a default. Reach for a switch, or its equivalent, when one value can take on several distinct options, and each one needs its own clear branch — like matching a day number to a day name.
Common beginner mistakes
- Cramming a big, complicated decision into a ternary. If the true/false branches are long or nested, a plain if/else reads far more clearly.
- Forgetting `break` in a switch (in languages that need it). This lets execution 'fall through' into the next case by mistake instead of stopping.
Try it — edit and run
Click the code to edit · press ⌘/Ctrl+↵ to run
Editable code. Tab and Shift+Tab indent. Press Escape, then Tab, to move focus out of the editor.
Status: adult
Day: WednesdayNot sure this is the right topic? See the learning paths → or where this leads →