switch
A snack machine has a code for each place: A1 gives water, A2 gives juice, B1 gives chips. You type a code, and the machine finds the place that matches. One value, many possible answers, each written next to its code.
switch
switch compares one value with a list of cases:
const code = "A2";
switch (code) {
case "A1":
console.log("Water");
break;
case "A2":
console.log("Juice");
break;
case "B1":
console.log("Chips");
break;
default:
console.log("No such slot");
}
Juice
Here is how to read it:
switch (code)takes the value to compare:"A2".- Each
caseholds a value. JavaScript compares theswitchvalue with each one, using===, from the top, until one matches:case "A2". - The lines under that case run, until
break.breakjumps out of theswitch. defaultruns when no case matches. Change the first line toconst code = "C9";, and the console saysNo such slot.
It does the same job as an else if chain that asks code === "A1", code === "A2", and so on. When every question compares the same value, switch is easier to read.
In a page
<label for="day">Club day</label>
<select id="day">
<option value="">Pick a day</option>
<option value="mon">Monday</option>
<option value="wed">Wednesday</option>
<option value="fri">Friday</option>
</select>
<p>Activity: <span id="activity">Pick a day first</span></p>
<script>
const day = document.querySelector("#day");
const activity = document.querySelector("#activity");
day.addEventListener("change", () => {
switch (day.value) {
case "mon":
activity.textContent = "Chess";
break;
case "wed":
activity.textContent = "Robots";
break;
case "fri":
activity.textContent = "Movie night";
break;
default:
activity.textContent = "Pick a day first";
}
});
</script>
Choose Wednesday: the page says Activity: Robots. Choose Pick a day again: no case matches, so default writes Pick a day first.
Break it on purpose
Remove the break of "A2":
switch (code) {
case "A1":
console.log("Water");
break;
case "A2":
console.log("Juice");
case "B1":
console.log("Chips");
break;
default:
console.log("No such slot");
}
Juice
Chips
Without break, JavaScript doesn't stop at the end of the case. It also runs the next case's lines, without checking its value, until it finds a break. So end every case with break.
Mission: Where to?
What you will see: when the page opens, the pass says Going to: No flight yet. Choose the flight SL-102, and it says Going to: Mars Relay.
Your pass shows the code of the flight, like SL-102. A passenger wants to read where it goes.
- On the pass, an element with the id
pass-destinationshows where the chosen flight goes, like the list says it. SL-101isMoon Base,SL-102isMars Relay,SL-103isEuropa Outpost,SL-104isLunar GatewayandSL-105isOrbital Yard.- With no flight chosen, it says
No flight yet: when the page opens, and when the passenger chooses Pick a flight again. #pass-flightstill shows the code.