- Home
- /
- Switch case
JavaScript Tutorial
IINTRODUCTION
JAVASCRIPT VARIABLES
JAVASCRIPT BASICS
JAVASCRIPT OBJECTS
DOM & BOM
OOPs
- Home
- /
- Switch case
Switch case
When you have to check many values against a single variable, writing a long if...else if...else
ladder can get messy. That’s where switch
comes in — it gives your code a cleaner, more readable structure.
Think of it like this:
Imagine you’re building a vending machine. Based on the button you press (say "A1"
), the machine checks the list of options and gives you a specific snack. If your input doesn’t match any item, it gives you an error message. That’s exactly what a switch
does.
Basic Syntax:
switch (expression) {
case value1:
// do something
break;
case value2:
// do something else
break;
...
default:
// do this if no case matches
}
expression
: The value you want to compare (e.g., a variable)case
: A possible value to check againstbreak
: Ends the case (if you leave it out, the next case also runs — called “fall-through”)default
: Runs if nocase
matches (optional but useful)
Example
let fruit = "apple";
switch (fruit) {
case "apple":
console.log("It's an apple!");
break;
case "banana":
console.log("It's a banana!");
break;
case "orange":
console.log("It's an orange!");
break;
default:
console.log("Unknown fruit.");
}
If you forget break
, the program will continue executing all the following cases, even if they don’t match. That’s usually not what you want—so always remember to break unless you want multiple cases to share the same result.
When to Use Switch:
When you’re checking one variable against many possible values
When you want cleaner syntax than repeating
else if
When each condition is distinct and exact