Labs ICT
Pro Login

Switch

Basic switch Statement

The switch statement evaluates an expression and executes code blocks based on matching cases.

const day = 3;
let dayName;
switch (day) {
  case 1:
    dayName = "Monday";
    break;
  case 2:
    dayName = "Tuesday";
    break;
  case 3:
    dayName = "Wednesday";
    break;
  case 4:
    dayName = "Thursday";
    break;
  case 5:
    dayName = "Friday";
    break;
  default:
    dayName = "Weekend";
}
console.log(dayName); // Wednesday
Try it Yourself →

Multiple Cases, Same Result

Group cases together when they should produce the same output.

const fruit = "apple";
switch (fruit) {
  case "apple":
  case "pear":
    console.log("Common fruit");
    break;
  case "durian":
    console.log("Strong smell!");
    break;
  default:
    console.log("Unknown fruit");
}
// Common fruit
Try it Yourself →

Fall-Through Behavior

Omitting break causes execution to fall through to the next case. This can be useful intentionally.

const level = 2;
switch (level) {
  case 1:
    console.log("Basic access");
  case 2:
    console.log("Standard access");
  case 3:
    console.log("Admin access");
    break;
  default:
    console.log("No access");
}
// Standard access
// Admin access
Try it Yourself →

switch with Strings

Switch works with strings just as well as numbers.

const command = "save";
switch (command) {
  case "save":
    console.log("Saving file...");
    break;
  case "load":
    console.log("Loading file...");
    break;
  case "delete":
    console.log("Deleting file...");
    break;
  default:
    console.log("Unknown command");
}
Try it Yourself →

Switch with Ranges (via true)

Use switch(true) to evaluate range-based conditions.

const score = 82;
let grade;
switch (true) {
  case score >= 90:
    grade = "A";
    break;
  case score >= 80:
    grade = "B";
    break;
  case score >= 70:
    grade = "C";
    break;
  default:
    grade = "F";
}
console.log(grade); // B
Try it Yourself →

Switch Inside Functions

Using switch inside a function keeps logic organized and reusable.

function getTaxRate(country) {
  switch (country) {
    case "US":
      return 0.07;
    case "UK":
      return 0.20;
    case "JP":
      return 0.10;
    case "DE":
      return 0.19;
    default:
      return 0;
  }
}

console.log(getTaxRate("JP")); // 0.1
console.log(getTaxRate("CA")); // 0
Try it Yourself →