By the end of this lesson, learners will:
switch
statement is and why it’s usedswitch
case
, break
, and default
correctlyswitch
over if...else
switch
for multi-branch decision-makingswitch
Statement?A switch
statement is a control flow structure that allows you to compare one value against many possible cases.
It is a cleaner and more readable alternative to writing multiple if...else if
statements.
switch
?Let’s say you’re building an app that gives the user a message based on the day of the week. You could use multiple if
statements:
if (day === "Monday") {
// ...
} else if (day === "Tuesday") {
// ...
} else if (day === "Wednesday") {
// ...
That works — but a switch
statement makes it much easier to read and maintain.
switch
Syntaxswitch (expression) {
case value1:
// code block
break;
case value2:
// code block
break;
default:
// code block
}
expression
is evaluated once.case
.break
statement prevents “fall-through.”default
block runs if no cases match.let day = "Wednesday";
switch (day) {
case "Monday":
console.log("Start of the week!");
break;
case "Wednesday":
console.log("Midweek check-in!");
break;
case "Friday":
console.log("Almost weekend!");
break;
default:
console.log("Have a nice day!");
}
Midweek check-in!
break
KeywordEach case
should end with a break
unless you want to run the next case (which is rare for beginners).
Without break
, JavaScript will fall through and run all remaining cases.
Example:
let mood = "happy";
switch (mood) {
case "happy":
console.log("Smile!");
case "sad":
console.log("Cheer up!");
}
Output:
Smile!
Cheer up!
🛑 That’s probably not what you intended. Add break
to fix it:
case "happy":
console.log("Smile!");
break;
default
CaseThe default
block is like an else
— it runs if none of the case
values match.
Example:
let fruit = "pear";
switch (fruit) {
case "apple":
console.log("Apples are sweet.");
break;
case "banana":
console.log("Bananas are yellow.");
break;
default:
console.log("Unknown fruit.");
}
Output:
Unknown fruit.
let light = "green";
switch (light) {
case "red":
console.log("Stop!");
break;
case "yellow":
console.log("Slow down.");
break;
case "green":
console.log("Go!");
break;
default:
console.log("Invalid color.");
}
Output: Go!
switch
?Use switch
when:
if...else if...else
chainsUse if
when:
Keyword | Description |
---|---|
switch | Evaluates one value |
case | A possible match value |
break | Exits the switch block after a match |
default | Runs if no case matches |