The switch Statement

Choose between many blocks based on one value.

Syntaxswitch (value) { case x: ...; break; }

The switch statement compares one value against several case options. It is a tidy alternative to a long if...else if chain.

Important parts

  • break stops the switch after a matching case runs.
  • default runs when no case matches.

Example

Try it yourself
Loading editor…
Press Run to execute the code.

When to use it

  • Route different HTTP method strings (GET, POST, PUT, DELETE) to separate handler functions.
  • Display a different notification icon based on the event type returned from an API.
  • Apply a different discount rate depending on which membership tier the user belongs to.

More examples

Switch on a string value

Uses switch to map a notification type string to its corresponding icon name.

Example · js
function getIcon(type) {
  switch (type) {
    case "error":   return "x-circle";
    case "warning": return "alert-triangle";
    case "success": return "check-circle";
    default:        return "info";
  }
}
console.log(getIcon("warning")); // "alert-triangle"

Fall-through for shared logic

Combines two cases without a break so Saturday and Sunday both fall through to the same message.

Example · js
const day = "Saturday";
switch (day) {
  case "Saturday":
  case "Sunday":
    console.log("Weekend – store closed");
    break;
  default:
    console.log("Weekday – store open");
}

Switch for HTTP method routing

Routes an HTTP method string to a handler description, normalising case with toUpperCase first.

Example · js
function handle(method) {
  switch (method.toUpperCase()) {
    case "GET":    return "fetch resource";
    case "POST":   return "create resource";
    case "DELETE": return "remove resource";
    default:       return "method not allowed";
  }
}
console.log(handle("post")); // "create resource"

Discussion

  • Be the first to comment on this lesson.