JS Switches

The switch statement is a control structure used to perform multiple operations based on different cases, often as an alternative to if-else statements.

Here's the basic syntax:

Syntax

 1switch (expression) {
 2  case value1:
 3    // code to be executed if expression matches value1
 4    break;
 5  case value2:
 6    // code to be executed if expression matches value2
 7    break;
 8  ...
 9  default:
10    // code to be executed if expression doesn't match any cases
11}

Example 1

 1let day = "Monday";
 2switch (day) {
 3  case "Monday":
 4    console.log("Today is Monday.");
 5    break;
 6  case "Tuesday":
 7    console.log("Today is Tuesday.");
 8    break;
 9  case "Wednesday":
10    console.log("Today is Wednesday.");
11    break;
12  default:
13    console.log("Today is some other day.");
14}
15// Output: Today is Monday.

Example 2

 1let grade = "A";
 2switch (grade) {
 3  case "A":
 4    console.log("Excellent!");
 5    break;
 6  case "B":
 7    console.log("Good.");
 8    break;
 9  case "C":
10    console.log("OK.");
11    break;
12  case "D":
13    console.log("You need to work harder.");
14    break;
15  case "F":
16    console.log("Fail.");
17    break;
18  default:
19    console.log("Invalid grade.");
20}
21// Output: Excellent!

Note that switch statements are commonly used for testing simple equality between the expression and the cases, but it is also possible to use other types of comparison (e.g. greater than, less than) and logical operators inside the cases.