Skip to main content

Switch Case

Switch case statements are a useful tool in TypeScript, a statically typed superset of JavaScript that adds optional types, classes and modules. They allow you to control the flow of your program by comparing a value against multiple variant expressions, and executing the first one that matches.

In this article, we'll cover everything you need to know about switch case statements in TypeScript. This includes their syntax, how to use them, and some best practices. By the end of this tutorial, you should be able to effectively use switch case statements in your TypeScript programs.

The Switch Case Syntax

The basic syntax of a switch case statement in TypeScript is as follows:

switch(expression) { 
case value1:
//Statements executed when the result of expression matches value1
break;
case value2:
//Statements executed when the result of expression matches value2
break;
...
default:
//Statements executed when none of the values match the value of the expression
break;
}

In the above syntax:

  • The switch keyword introduces the switch case statement.
  • The expression within the parentheses after switch is evaluated once.
  • The case keyword introduces a case to compare the expression against.
  • If the value of expression matches a case, the statements within that case are executed.
  • The break keyword ends the switch case statement. If break is omitted, execution will "fall through" to the next case.
  • The default keyword introduces a fallback case to be executed if none of the case values match the expression.

Using Switch Case Statements

Here's an example of how you might use a switch case statement in TypeScript:

let day: number = 4;

switch(day) {
case 0:
console.log("Sunday");
break;
case 1:
console.log("Monday");
break;
case 2:
console.log("Tuesday");
break;
case 3:
console.log("Wednesday");
break;
case 4:
console.log("Thursday");
break;
case 5:
console.log("Friday");
break;
case 6:
console.log("Saturday");
break;
default:
console.log("Invalid day");
break;
}

In this example, if day is 4, the console logs "Thursday". If day is a number not between 0 and 6, the console logs "Invalid day".

Best Practices

When using switch case statements in TypeScript, there are a few best practices to keep in mind:

  1. Always include a default case: This ensures that your code will always do something, even if none of the case values match the expression.
  2. Don't forget the break keyword: If you forget to include break after a case, execution will "fall through" to the next case. This can lead to unexpected behavior.
  3. Use switch case when you have three or more conditions to check: If you only have two conditions to check, an if...else statement is more suitable.

Now that you've learned about switch case statements in TypeScript, try to incorporate them into your code. They can help make your code cleaner and easier to read, especially when dealing with multiple conditions. Happy coding!