TypeScript Switch Statement
Learn how to use switch, case, break, and default statements to select the appropriate execution path based on a value, with practical examples and expected outputs.
What Will We Learn?
The switch statement makes programs easier to organize when a single expression needs to be checked against several possible values.
- Understand switch and case statements.
- Use the break statement.
- Handle unmatched values using default.
- Group multiple cases for the same result.
- Understand fall-through behavior.
- Implement practical menu and course-selection examples.
Switch Statement Workflow
Follow these steps to understand how the switch statement selects a matching case.
Step 1
Get ValueEvaluate the expression.
Step 2
Check CasesFind a matching case.
Step 3
Execute BlockRun the selected case.
Step 4
FinishExit with break or continue execution.
1. Switch Statement Syntax
A switch statement contains an expression, one or more case labels, and an optional default case.
Syntax
switch (expression) {
case value1:
// Statements
break;
case value2:
// Statements
break;
default:
// Default statements
}
Important Parts
| Keyword | Purpose |
|---|---|
switch |
Evaluates the expression to select a case. |
case |
Specifies a value to match. |
break |
Exits the switch statement. |
default |
Provides a fallback when no case matches. |
2. Basic Switch Statement
A switch statement compares its expression with case values and executes the matching case.
Example
let day: number = 2;
switch (day) {
case 1:
console.log("Monday");
break;
case 2:
console.log("Tuesday");
break;
case 3:
console.log("Wednesday");
break;
default:
console.log("Invalid Day");
}
Expected Output
Tuesday
The value of day is 2, so case 2 matches.
The Tuesday message is displayed, and
break exits the switch.
3. Switch with String Values
A switch statement can also compare string values. This is useful for checking categories, commands, status names, and selections.
Example
let courseName: string = "TypeScript";
switch (courseName) {
case "Java":
console.log("Java Full Stack Course");
break;
case "Python":
console.log("Python Full Stack Course");
break;
case "TypeScript":
console.log("TypeScript Training");
break;
default:
console.log("Course Not Found");
}
Expected Output
TypeScript Training
The string value matches the TypeScript case.
String matching is case-sensitive, so
"typescript" would not match
"TypeScript".
4. Understanding the Break Statement
The break statement exits the nearest
enclosing switch statement. Without a break or
another control-flow statement, execution can
continue into the following case.
Example
let option: number = 1;
switch (option) {
case 1:
console.log("Add Student");
break;
case 2:
console.log("Update Student");
break;
case 3:
console.log("Delete Student");
break;
default:
console.log("Invalid Option");
}
Expected Output
Add Student
After displaying Add Student, the break statement prevents execution from continuing into cases 2 and 3.
5. Default Case
The default case is executed when
no case value matches the switch expression.
It is optional, but useful for handling unexpected values.
Example
let menuOption: number = 5;
switch (menuOption) {
case 1:
console.log("View Students");
break;
case 2:
console.log("Add Student");
break;
case 3:
console.log("Update Student");
break;
default:
console.log("Invalid Menu Option");
}
Expected Output
Invalid Menu Option
Since 5 does not match any defined case, the default block executes.
6. Grouping Multiple Cases
Multiple case labels can share the same code block. This is useful when different values should produce the same result.
Example
let day: number = 6;
switch (day) {
case 1:
case 2:
case 3:
case 4:
case 5:
console.log("Weekday");
break;
case 6:
case 7:
console.log("Weekend");
break;
default:
console.log("Invalid Day");
}
Expected Output
Weekend
Cases 6 and 7 share the same block, so either value displays Weekend.
7. Fall-Through Behavior
Fall-through occurs when a matching case continues executing statements from later cases because there is no break or other control-flow statement to stop it.
Example
let value: number = 1;
switch (value) {
case 1:
console.log("One");
case 2:
console.log("Two");
break;
default:
console.log("Other");
}
Expected Output
One
Two
Case 1 matches and displays One. Since there is no break after case 1, execution continues into case 2 and displays Two.
break after a case when you want
the switch statement to stop at that case.
Intentional fall-through should be clearly documented.
8. Switch with Enum
TypeScript enums define a set of named constants. A switch statement can use an enum value to select the appropriate block.
Example
enum OrderStatus {
Pending,
Approved,
Rejected
}
let status: OrderStatus = OrderStatus.Approved;
switch (status) {
case OrderStatus.Pending:
console.log("Order Pending");
break;
case OrderStatus.Approved:
console.log("Order Approved");
break;
case OrderStatus.Rejected:
console.log("Order Rejected");
break;
}
Expected Output
Order Approved
The status matches OrderStatus.Approved,
so the corresponding message is displayed.
9. Switch vs If-Else
Both switch and if-else statements control program flow, but each is suitable for different situations.
| Feature | Switch | If-Else |
|---|---|---|
| Best suited for | Matching one expression against case values. | Ranges, comparisons, and complex conditions. |
| Matching | Uses strict equality for case matching. | Uses whatever conditions you write. |
| Multiple fixed options | Often easy to organize. | Can require many else-if branches. |
| Ranges | Not directly supported by ordinary case labels. | Easy to express using comparison operators. |
| Fall-through | Can occur without break or another exit. | Only the selected branch runs unless control flow changes. |
Practical Example: CIIT Course Selection
Let's use a switch statement to display course information based on the course selected by a student.
Example
let selectedCourse: string = "Dot Net";
switch (selectedCourse) {
case "Java":
console.log("Java Full Stack");
console.log("Language: Java");
break;
case "Python":
console.log("Python Full Stack");
console.log("Language: Python");
break;
case "Dot Net":
console.log("Dot Net Full Stack");
console.log("Language: C#");
break;
default:
console.log("Course Not Available");
}
Expected Output
Dot Net Full Stack
Language: C#
The selected course is Dot Net, so its case executes. The break statement prevents the next case from running.
Common Mistakes
-
Forgetting
breakwhen fall-through is not intended. - Forgetting to include a default case when unexpected values need handling.
- Assuming that different string casing will match the same case.
- Expecting case labels to check numeric ranges automatically.
- Using switch when a simple if/else condition would be clearer.
Practice Task
Create a TypeScript program for a simple student management menu.
- Option 1: View Students
- Option 2: Add Student
- Option 3: Update Student
- Option 4: Delete Student
- Any other option: Invalid Option
Store the selected option in a variable and use a switch statement to display the appropriate message.
Hint
let option: number = 2;
switch (option) {
case 1:
console.log("View Students");
break;
case 2:
console.log("Add Student");
break;
case 3:
console.log("Update Student");
break;
case 4:
console.log("Delete Student");
break;
default:
console.log("Invalid Option");
}
Expected Output
Add Student
Summary
In this lesson, we learned how to use switch statements, case labels, break, default, grouped cases, fall-through, and enums. We also compared switch with if-else and created a practical course-selection example.
Key Point: Switch is useful for selecting among fixed values. Use break when you want to exit a case instead of continuing into the next case.