How to use switch statements

Match a value

A switch compares with strict equality. break prevents execution from falling through into the next case.

const role = "editor";
switch (role) {
  case "admin":
    console.log("Full access");
    break;
  case "editor":
    console.log("Can edit");
    break;
  default:
    console.log("Read only");
}

Group several cases

Intentional fall-through lets cases share a result. Add a comment when the grouping might not be obvious.

const day = "Saturday";
switch (day) {
  case "Saturday":
  case "Sunday":
    console.log("Weekend");
    break;
  default:
    console.log("Weekday");
}

Return from a switch

Inside a function, returning from each case removes the need for break.

function shippingZone(code) {
  switch (code) {
    case "KE": return "East Africa";
    case "FR": return "Europe";
    default: return "Other";
  }
}
console.log(shippingZone("KE"));

Choose switch appropriately

  • Use it when one expression has several discrete values
  • Use if/else for ranges and unrelated conditions
  • Always consider a default case
  • Do not forget break unless fall-through is intentional