Learn Create Your Own Split Screen

Next Page

Remember this example?
if (day == "Monday") { alert("I don't like Mondays"); } else if (day == "Saturday" || day == "Sunday"){ alert("Hooray, the weekend"); } else if (day == "Wednesday") { alert("Some people call this 'hump day'"); } else if (day == "Friday") { alert("Weekend tomorrow!"); } else if (day == "Tuesday" || day = "Thursday") { alert("Just another day..."); } else { alert("Invalid day. Please reboot the universe."); }
Here it is rewritten as a switch. Two things to note:
  1. We're making productive use of fallthrough, because the Saturday case has no lines of code at all, and just falls though and does the same as for Sunday. I've used line spacing to make my intent clearer.
  2. We use the special "default" keyword which is like a "catch-all else" for switch statements. If none of the cases apply, the default will.
switch (day) { case "Monday: alert("I don't like Mondays"); break; case "Saturday": case "Sunday": alert("Hooray, the weekend"); break; case "Wednesday": alert("Some people call this 'hump day'"); break; case "Friday": alert("Weekend tomorrow!"); break; case "Tuesday": case "Thursday": alert("Just another day..."); break; default: alert("Invalid day. Please reboot the universe."); }