TypeScript switch Statement

Note: If you're new to TypeScript, check our Getting Started with TypeScript tutorial first.


The TypeScript switch...case statement executes different blocks of code based on the value of a given expression.

Example

let trafficLight: string = "green";
let message: string = ""
 
switch (trafficLight) {
    case "red":
        message = "Stop immediately.";
        break;
    case "yellow":
        message = "Prepare to stop.";
        break;
    case "green":
        message = "Proceed or continue driving.";
        break;
    default:
        message = "Invalid traffic light color.";
}
 
console.log(message)
 
// Output: Proceed or continue driving.

The above program checks the value of trafficLight and prints its corresponding meaning. If the value doesn't match any of the specified cases, it prints Invalid traffic light color.


Syntax of the switch...case Statement

switch (expression) {

    case value1:
        // Code block to be executed
        // if expression matches value1
        break;

    case value2:
        // Code block to be executed
        // if expression matches value2
        break;

    ...

    default:
        // Code block to be executed
        // if expression doesn't match any case
}

Here,

  1. The switch statement first evaluates the expression.
  2. After that, it compares the result against value1. If a match is found, the corresponding code block is executed. Then, the break statement immediately stops further checking of other cases.
  3. If there's no match for value1, the program compares the result with the next specified case value (value2). This process continues until a matching case is found.
  4. If none of the case values match, the code block in the default block is executed.

Let's try to understand this process with the flowchart below.


Flowchart of switch Statement

Flowchart of TypeScript switch statement
Flowchart of TypeScript switch statement

Example 1: Simple Program Using switch...case

Suppose we want to display a message based on the current day of the week. Let's look at the example below to see how we can achieve this using switch...case.

let day: number = 3; 

switch (day) {

    case 1:
        console.log("Sunday");
        break;

    case 2:
        console.log("Monday");
        break;

    case 3:
        console.log("Tuesday");
        break;

    case 4:
        console.log("Wednesday");
        break;

    case 5:
        console.log("Thursday");
        break;

    case 6:
        console.log("Friday");
        break;

    case 7:
        console.log("Saturday");
        break;

    default:
        console.log("Invalid Day");
}

Output

Tuesday

This program prints the day based on the number stored in the day variable (1 for Sunday, 2 for Monday, and so on).

Here, the switch statement checks the value of day against a series of cases:

  1. First, it checks day against case 1. Since it doesn't match, this case is skipped.
  2. Next, it checks day against case 2. Since it doesn't match, this case is skipped.
  3. Then, it checks day against case 3. Since there's a match, its code block is executed (Tuesday is printed).
  4. After printing Tuesday, a break statement is encountered, which terminates the switch statement.

Note: Because of TypeScript's strict type checking, you can't check variables/expressions of one type with case values of other types. For example,

let day: number = 3; 

switch (day) {

    // Error due to comparison between number variable and string literal
    case "1":
        console.log("Sunday");
        break;

    ... ... ...
}

Example 2: Simple Calculator Using switch...case

// Take user input for first number
let userInput: string | null = prompt("Enter the value of number1: ");
const number1: number = Number(userInput);

// Take user input for second number
userInput = prompt("Enter the value of number2: ");
const number2 = Number(userInput);

// Take user input to select an operator
const operator: string | null = prompt("Enter an operator ( either +, -, * or / ): ");

// Variable to store the result of calculation
let result: number;

switch(operator) {

    case "+":
        result = number1 + number2;
        console.log(`${number1} + ${number2} = ${result}`);
        break;

    case "-":
        result = number1 - number2;
        console.log(`${number1} - ${number2} = ${result}`);
        break;

    case "*":
        result = number1 * number2;
        console.log(`${number1} * ${number2} = ${result}`);
        break;

    case "/":
        result = number1 / number2;
        console.log(`${number1} / ${number2} = ${result}`);
        break;

    default:
        console.log("Invalid operator");
}

Sample Output 1

Enter the value of number1: 6
Enter the value of number2: 3
Enter an operator ( either +, -, * or / ): *
6 * 3 = 18

Sample Output 2

Enter the value of number1: 6
Enter the value of number2: 3
Enter an operator ( either +, -, * or / ): +
6 + 3 = 9

In the above program, we prompted the user to:

  • Enter two numbers: number1 and number2.
  • Select an operator: +, -, *, or /.

Based on the user input, the switch statement performs the corresponding calculation.

Note: Here, we have used template literal `${number1} + ${number2} = ${result}` that combines text and variable into one string.

It shows the values of number1, number2, and result directly in the message, like 5 + 3 = 8. To learn more about template literals, visit TypeScript Template Literals.


More on TypeScript switch Statement

The default case is optional.

It is not necessary to use the default case in TypeScript. For example,

let country: string = "Nepal";

switch (country) {
    case "USA":
        console.log("American");
        break;
    case "UK":
        console.log("British");
        break;
    case "Japan":
        console.log("Japanese");
}

console.log("Code after switch statement")

// Output: Code after switch statement

We haven't used a default case in the program above. Moreover, the value of the country variable doesn't match any of the cases in the switch statement.

In such cases, the switch statement is skipped entirely and the program flow goes to the line that comes after the body of the switch statement.

What happens when we use a switch statement without break?

So far, we have used a break statement inside each case block. For example,

case 2:
    console.log("Monday");
    break;

The break statement terminates the execution of the switch statement once a matching case has been found.

Without break, the program would continue executing subsequent cases even after finding a match. For example,

let fruit: string = "banana";

switch (fruit) {
    case "apple":
        console.log("Apple case");
    case "banana":
        console.log("Banana case");
    case "orange":
        console.log("Orange case");       
    default:
        console.log("Unknown fruit");
}

Output

Banana case
Orange case
Unknown fruit
How can we use a single block of code for multiple case values?

Sometimes, we may want multiple case values to trigger the same block of code. For this, we can use multiple cases with a single block.

Let's look at an example to understand this clearly.

// Program to categorize age

let age: number = 19;

switch (age) {

    // When age is 13, 14, or 15
    case 13:
    case 14:
    case 15:
        console.log("Early Teen")
        break;

    // When age is 16 or 17
    case 16:
    case 17:
        console.log("Mid Teen");
        break;

    // When age is 18 or 19
    case 18:
    case 19:
        console.log("Late Teen");
        break;

    // When age is none of the above
    default:
        console.log("Other Age Group");
}

Output

Late Teen

In this program, we have grouped multiple cases together, which allows us to use a single block of code for all the cases in the group. These groups are:

  • cases 13, 14, and 15 - Prints Early Teen to the screen.
  • cases 16 and 17 - Prints Mid Teen to the screen.
  • cases 18 and 19 - Prints Late Teen to the screen.

Since 19 matches the second case in the third group (case 19), Late Teen is printed as an output.

Comparison between switch statement and if...else statement.

Both switch...case and if...else statements are used for decision-making. However, they are useful in different conditions:

  • switch - Use it to check for a large number of conditions based on the same expression, which can be more readable than if...else.
  • if...else - Use it for complex logical conditions that can't be easily expressed as discrete cases.

Let's look at two programs that perform the same task, one by using a switch statement and another by using if...else:

// Program using switch statement 

let color: string = "green";

switch (color) {
    case "red":
        console.log("Stop");
        break;
    case "yellow":
        console.log("Caution");
        break;
    case "green":
        console.log("Go");
        break;
    default:
        console.log("Invalid color");
}

// Output: Go

In the above program, the color variable is compared against each case. When it matches the case "green", Go is printed as output.

// Program using if...else statement

let color: string = "green";

if (color === "red") {
    console.log("Stop");
}
else if (color === "yellow") {
    console.log("Caution");
}
else if (color === "green") {
    console.log("Go");
}
else {
    console.log("Invalid color");
}

// Output: Go

Here, the if...else statement checks the value of color against various conditions.

When color matches "green", the corresponding block executes, printing Go as the output.


Also Read:

Did you find this article helpful?

Our premium learning platform, created with over a decade of experience and thousands of feedbacks.

Learn and improve your coding skills like never before.

Try Programiz PRO
  • Interactive Courses
  • Certificates
  • AI Help
  • 2000+ Challenges