freecoding.school100% FREE · NO SIGNUP
Script SpringsISSUE #24 of 29

switch · case · break · default

SparkyVSNaN the Trickster
Sparky saysswitch matches one value against many cases — cleaner than a long if/else chain.

switch (x) compares x (with ===) against each case. Each case needs a break or execution "falls through" to the next — sometimes intentional for grouping. default handles the rest. For complex conditions, an object lookup is often cleaner than switch.

Power-ups you unlock

NaN the Trickster attacks — common mistakes

Boss battleWrite a switch mapping a day number to a name, with a default.

Example code

<!doctype html><html><head><meta charset="utf-8"></head>
<body style="background:#06040d;color:#e6e0ff;font-family:monospace;padding:20px"><pre id="o"></pre>
<script>function day(n){switch(n){case 0:return 'Sun';case 6:return 'Sat';default:return 'weekday';}}
document.getElementById('o').textContent=[0,3,6].map(day).join(' ');</script></body></html>
▶ Open the interactive comic issue
‹ If · Else · Else IfFor Loops · Classic ›