Operators & LogicExtra· 30 min read

Switch & the Ternary Operator

Two cleaner ways to write certain decisions — switch for many cases, ternary for quick one-liners.

What you will learn

  • Use a switch statement
  • Write a ternary expression
  • Choose the clearest tool

switch — many fixed cases

When you compare one value against many options, switch is tidier than a long if/else chain.

switch with cases and break
<script>
  let day = 3;
  let name;
  switch (day) {
    case 1: name = "Monday"; break;
    case 2: name = "Tuesday"; break;
    case 3: name = "Wednesday"; break;
    default: name = "Other";
  }
  document.write(name);
</script>
Live preview

Here is how a switch runs step by step:

  1. switch (day) takes the value to test — here day is 3.
  2. It compares that value against each case from top to bottom.
  3. case 1 and case 2 do not match, so they are skipped.
  4. case 3 matches, so name = "Wednesday" runs.
  5. break stops the switch right there. (default only runs if no case matched.)

Note: Output: Wednesday

Watch out: Do not forget break after each case — without it, JavaScript “falls through” and runs the next cases too.

Ternary — a one-line if/else

The ternary operator condition ? a : b returns a if true, else b — perfect for short choices.

condition ? ifTrue : ifFalse
<script>
  let age = 20;
  let status = age >= 18 ? "Adult" : "Minor";
  document.write(status);
</script>
Live preview

Read it as a quick question: "Is age >= 18?" Since age is 20, the answer is yes, so the value before the colon ("Adult") is chosen and stored in status. If age were under 18, the value after the colon ("Minor") would be chosen instead.

Note: Output: Adult

Q. What keyword stops a switch case from falling through to the next?

Answer: break ends the current case. Without it, execution continues into the following cases.

✍️ Practice

  1. Use a switch to turn a number 1–7 into a day name.
  2. Rewrite a simple if/else as a ternary.

🏠 Homework

  1. Build a tiny calculator that uses switch on an operator (+, -, *, /).
Want to learn this with a mentor?

CodingClave runs guided, project-based training (28-day, 45-day & 6-month batches).

Explore Training →