JavaScript Switch

Choose between many cases.

✍️ 3 exercises + code challenge in this lesson

A switch statement compares one value against many cases. It is often clearer than a long chain of else if.

  • Each case is compared with ===.
  • break stops the switch; without it, execution "falls through" to the next case.
  • default runs when no case matches.

Key Takeaways: JavaScript Switch

Mastering JavaScript Switch helps you write clean and reliable JavaScript code. Follow standard conventions, test edge cases, and keep logic simple. Try running the code example below and complete the exercises to build confidence.

JavaScript Switch Code Example

JavaScript
<pre id="out"></pre>
<script>
const log = (...a) => document.getElementById("out").textContent += a.join(" ") + "\n";
const days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
const today = new Date().getDay();
let plan;

switch (today) {
  case 0:
  case 6:
    plan = "Weekend: time to relax!";
    break;
  case 5:
    plan = "Friday: almost there.";
    break;
  default:
    plan = "A working day: keep coding.";
}

log(days[today] + ":", plan);
</script>
Free sign-in required · Google login available

JavaScript Switch Practice Exercises

Check what you learned in “JavaScript Switch”.

/ 3 solved
Fill in the blank

Stop the switch after a match.

switch (day) {
  case 0:
    log("Sunday");
    ;
}
✓ Correct! Not quite. Try again.
Multiple choice

Which keyword runs when no case matches?

✓ Correct! Not quite. Try again.
Code challenge

Use a switch on color: log "Stop" for "red", "Go" for "green", otherwise "Wait".

Write the code in the live editor. Your answer is checked automatically.

Free sign-in required · Google login available

to save your exercise progress.
Finished this lesson?
Mark it complete to track your progress.

Stuck on something?

Ask the community in the CodesInTech forum.

Need a developer?

Learning on your own is great — and when you need professional help, our team builds custom software, websites and mobile apps for clients worldwide.

Explore Our Services