JavaScript Switch Statement
8 April 2025 | Category: JavaScript
The switch
statement is used to perform different actions based on different conditions. It’s a cleaner way to write multiple if...else if
statements when checking the same variable or expression.
✅ Syntax
switch (expression) {
case value1:
// Code to run if expression === value1
break;
case value2:
// Code to run if expression === value2
break;
...
default:
// Code to run if no case matches
}
break
stops the execution after a case is matched.default
is optional and runs when no case matches.
🔍 Example:
let day = "Tuesday";
switch (day) {
case "Monday":
console.log("Start of the week.");
break;
case "Tuesday":
console.log("It's Tuesday!");
break;
case "Wednesday":
console.log("Halfway there.");
break;
default:
console.log("Another day.");
}
Output:
It's Tuesday!
⚠️ Why use break
?
If you don’t use break
, JavaScript will continue to run the next cases, even if a match is found.
let fruit = "apple";
switch (fruit) {
case "apple":
console.log("Apples are red.");
case "banana":
console.log("Bananas are yellow.");
default:
console.log("Fruit not found.");
}
Output:
Apples are red.
Bananas are yellow.
Fruit not found.
✅ To fix it, add break
after each case.
🔁 Using default
The default
case is like the else
block. It runs when none of the other cases match.
let color = "blue";
switch (color) {
case "red":
console.log("Stop!");
break;
case "green":
console.log("Go!");
break;
default:
console.log("Unknown color.");
}
Output:
Unknown color.
🔢 Example with Numbers
let grade = 90;
switch (true) {
case (grade >= 90):
console.log("Grade A");
break;
case (grade >= 80):
console.log("Grade B");
break;
default:
console.log("Keep trying!");
}
📌 Summary
switch
is used when checking a single expression against multiple values.- Each
case
must end with abreak
(to avoid fall-through). - Use
default
for unmatched conditions.