Switch-case statement in typescript with examples

Switch statement in typescript with examples:

switch statement is used to run a block of code based on the result of an expression. Unlike the if-else block, we can use switch with any type of return value of an expression, not only boolean.

In this post, I will show you how to use switch with an example.

Syntax of switch:

switch(expression){
    case expression1:
        break;
    case expression2:
        break;
        ...
        ...
        ...
    default:
        break;
}
  • Based on the value of expression, the control moves to the case statement that matches this expression.
  • We can have unlimited numbers of case blocks.
  • The break statement at the end of a case statement indicates that the control exits the switch block once it executes the code for a case block.
  • The default case is optional. This case runs if the given expression doesn’t match with any of the cases.

Example 1: Switch block with numbers:

Let’s take a look at the below example:

let givenValue = 1;

switch(givenValue){
    case 0:
        console.log('Zero');
        break;
    case 1:
        console.log('One');
        break;
    case 2:
        console.log('Two');
        break;
    case 3:
        console.log('Three');
        break;
    case 4:
        console.log('Four');
        break;
    case 5:
        console.log('Five');
        break;
}

In this example, based on the value of givenValue, it prints a message if givenValue is 0,1,2,3,4 or 5. For any other values, it will not print any message.

Example 2: Switch block with characters:

We can also use a switch block with characters:

let givenValue = 'a';

switch(givenValue){
    case 'a':
        console.log('Vowel');
        break;
    case 'e':
        console.log('Vowel');
        break;
    case 'i':
        console.log('Vowel');
        break;
    case 'o':
        console.log('Vowel');
        break;
    case 'u':
        console.log('Vowel');
        break;
    default:
        console.log('Consonant');
        break;
}

Based on the value of givenValue, it will print a message Vowel or Consonant.

You might also like: