Javatpoint Logo
Javatpoint Logo

TypeScript Switch Statement

The TypeScript switch statement executes one statement from multiple conditions. It evaluates an expression based on its value that could be Boolean, number, byte, short, int, long, enum type, string, etc. A switch statement has one block of code corresponding to each value. When the match is found, the corresponding block will be executed. A switch statement works like the if-else-if ladder statement.

The following points must be remembered in a switch statement:

  • There can be N number of cases inside a switch statement.
  • The case values must be unique.
  • The case values must be constant.
  • Each case statement has a break statement at the end of the code. The break statement is optional.
  • The switch statement has a default block which is written at the end. The default statement is optional.

Syntax

The switch statement contains the following things. There can be any number of cases inside a switch statement.

Case: The case should be followed by only one constant and then a semicolon. It cannot accept another variable or expression.

Break: The break should be written at the end of the block to come out from the switch statement after executing a case block. If we do not write break, the execution continues with the matching value to the subsequent case block.

Default: The default block should be written at the end of the switch statement. It executes when there are no case will be matched.

TypeScript Switch Statement

Example

Output:

TypeScript Switch Statement

Switch case with String

In this example, we have a string variable grade. The switch statement evaluates grade variable value and match with case clauses and then execute its associated statements.

Output:

TypeScript Switch Statement

Switch Case with Enum

In TypeScript, we can use the switch case with Enum in the following ways.

Example

Output:

TypeScript Switch Statement

TypeScript Switch Statement is fall-through.

The TypeScript switch statement is fall-through. It means if a break statement is not present, then it executes all statements after the first match case.

Example

Output:

TypeScript Switch Statement




Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA