switch statements
The full text of this chapter, to read or revisit. To practise, do the exercises.
βΆ Do the exercisesExercise 1 β The switch Statement
When you compare the same variable against many exact values, an else if chain gets repetitive. JavaScript has a cleaner tool for that: switch.
let codemonType = "water";
switch (codemonType) {
case "fire":
console.log("Pyrochu joins the battle!");
break;
case "water":
console.log("Aquachu joins the battle!");
break;
case "plant":
console.log("Florachu joins the battle!");
break;
}switch takes the value of codemonType and looks for the case that matches it exactly. Here it finds case "water" and runs its code. Try changing the type!
Exercise 2 β break and default
Two keywords make switch work properly:
1. break stops the switch after a case. Without it, JavaScript keeps running the next cases too β that's called fall-through!
2. default runs when no case matches, like a final else.
let attack = "unknown-move";
switch (attack) {
case "thunder":
console.log("Zap strikes!");
break;
case "flame":
console.log("Pyrochu burns!");
break;
default:
console.log("Nothing happens...");
}// Now watch what happens WITHOUT break:
let berry = "red";
switch (berry) {
case "red":
console.log("Spicy!");
case "blue":
console.log("Sweet!");
case "green":
console.log("Sour!");
}All three messages print! After matching case "red", the code falls through every following case. Almost always, you want a break at the end of each case.
Exercise 3 β Predict the switch
What will this code print?
let badge = "silver";
switch (badge) {
case "gold":
console.log("Elite trainer");
break;
case "silver":
console.log("Confirmed trainer");
break;
default:
console.log("Rookie trainer");
}Confirmed trainerElite trainerRookie trainerConfirmed trainer then Rookie trainerHint : Find the case matching the value exactly, and note that each case ends with a break.
Exercise 4 β Complete the switch
Complete the potion dispenser with the three missing keywords.
Hint : One keyword opens the structure, one introduces each value, one handles the "no match" situation.
Exercise 5 β The Missing break
The break after the first case was forgotten. What will this print?
let move = "splash";
switch (move) {
case "splash":
console.log("Water everywhere!");
case "bubble":
console.log("Bubbles float up!");
break;
case "dive":
console.log("Aquachu dives!");
break;
}Water everywhere! then Bubbles float up!Water everywhere!Hint : Without break, execution continues into the next case... until it finally meets a break.
Exercise 6 β Arena Doors
Each arena door leads to a different battle. Complete the switch so it works correctly, without fall-through.
Hint : door contains a number, so the case value must be a number too β switch compares strictly, like ===.
Exercise 7 β switch Keywords
Match each keyword with its role in a switch.
switchcasebreakdefaultExercise 8 β switch or else if?
So when should you use which? Simple rule:
1. switch: one variable compared to exact values ("fire", "water", 1, 2...)
2. else if chain: conditions with ranges or logic (hp > 50, level >= 10 && hasBadge...)
// switch CANNOT do this:
// case hp > 50: β not an exact value
// For ranges, use else if:
if (hp > 50) {
console.log("Strong");
} else if (hp > 20) {
console.log("Weak");
}Strict Comparison
switch compares with strict equality (===). So case "5" will never match the number 5 β types must match too!
Exercise 9 β Right Tool for the Job
Which situation is a perfect fit for a switch ?
"fight", "heal", "run"level >= 10 && hasBadgeHint : switch shines when one variable is compared against a list of exact values.
Exercise 10 β The Move Selector
Build Zap's move selector with a switch on move:
1. "thunder" prints "Zap uses Thunder! 40 damage"
2. "spark" prints "Zap uses Spark! 20 damage"
3. "charge" prints "Zap charges energy..."
4. any other value prints "Zap doesn't know this move!"
Don't forget the break after each case!
let move = "spark";
// Write your switch here