TypeScript - Switch Case Statement
Introduction
The switch statement is used to perform multiple possible conditions by comparing an expression to different values. It is often preferred over multiple if-else statements when comparing a single variable against many possible values.
Syntax:
switch (expression) {
case value1:
// Code to execute if expression equals value1
break;
case value2:
// Code to execute if expression equals value2
break;
// More cases can follow
default:
// Code to execute if no case matches
}- The expression is evaluated once.
- The value of the expression is compared with each
casevalue. - If a match is found, the corresponding code block is executed.
- The
breakstatement is used to exit theswitchstatement once a match is found. - The
defaultblock is executed if no cases match the expression.
Example 1: Basic Switch Case
let day = 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");
}Output:
TuesdayExample 2: Switch Case with Multiple Matches
let fruit = "apple";
switch (fruit) {
case "apple":
console.log("This is an apple.");
break;
case "banana":
console.log("This is a banana.");
break;
case "orange":
console.log("This is an orange.");
break;
default:
console.log("Unknown fruit");
}Output:
This is an apple.Example 3: Switch Case Without Break
let score = 85;
switch (score) {
case 90:
case 85:
console.log("Grade B");
break;
case 80:
console.log("Grade C");
break;
default:
console.log("Grade D");
}Output:
Grade BConclusion
The switch statement is a powerful control structure in TypeScript that simplifies checking multiple possible values for a single expression. It is useful when comparing a variable against several values and helps avoid multiple if-else statements.