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:
switch(expression){ case expression1: //code to be executed; break; //optional case expression2: //code to be executed; break; //optional ........ default: //when no case is matched, this block will be executed; break; //optional }
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.
let a = 3; let b = 2; switch (a+b){ case 1: { console.log("a+b is 1."); break; } case 2: { console.log("a+b is 5."); break; } case 3: { console.log("a+b is 6."); break; } default: { console.log("a+b is 5."); break; } }
let grade: string = "A"; switch (grade) { case'A+': console.log("Marks >= 90"+"\n"+"Excellent"); break; case'A': console.log("Marks [ >= 80 and <90 ]"+"\n"+"Good"); break; case'B+': console.log("Marks [ >= 70 and <80 ]"+"\n"+"Above Average"); break; case'B': console.log("Marks [ >= 60 and <70 ]"+"\n"+"Average"); break; case'C': console.log("Marks < 60"+"\n"+"Below Average"); break; default: console.log("Invalid Grade."); }
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.
In TypeScript, we can use the switch case with Enum in the following ways.
enum Direction { East, West, North, South }; var dir: Direction = Direction.North; function getDirection() { switch (dir) { case Direction.North: console.log('You are in North Direction'); break; case Direction.East: console.log('You are in East Direction'); break; case Direction.South: console.log('You are in South Direction'); break; case Direction.West: console.log('You are in West Direction'); break; } } getDirection();
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.
let number = 20; switch(number) { //switch cases without break statements case 10: console.log("10"); case 20: console.log("20"); case 30: console.log("30"); default: console.log("Not in 10, 20 or 30"); }