Conditional Statements in TypeScript – switch

There is another conditional statement that we use use in TypeScript. That is Switch Case Statement.

Basic Syntax of switch statement is:

switch(variable) { 
   case constant1: { 
      //statements; 
      break; //breaks the flow of the execution
   } 
   case constant2: { 
      //statements; 
      break; 
   } 
   default: { //optional
      //statements; 
      break; 
   } 
} 
  • We test the cases against a defined value. Whichever case matches the value, that case is executed.
  • We put break statement to stop the execution of code after that case.
  • default is used when the defined value does not matches any case. This is optional.
  • There can be any number of cases in switch statements.
  • Cases should have unique constants to match the variable of Switch.
  • Data Type of Switch variable and case constant should be same.
  • Case contacts should only be constants. They should not be expressions or variable.

Below is an example when the defined value matched one of the case.

var weeknum:number = 4;
switch(weeknum){
    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 Value");

}

Below is the output of above code.

Below is an example for default statement.

var weeknum:number = 9;
switch(weeknum){
    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 Value");

}

Below is the output of above code:

Unknown's avatar

Author: Akanksha Gupta

I am a developer and working on SharePoint and Project Server in an MNC. I have more than 10 years of experience in the same field.

Leave a comment

Design a site like this with WordPress.com
Get started