JavaScript Tutorial · Control Flow · Lesson 15 of 44

JavaScript Switch

Choose between many cases with switch — and don't forget break.

switch

switch compares one value against several cases using strict equality (===):

Example 1Try it yourself
const day = 3;
switch (day) {
  case 1:
    console.log("Monday");
    break;
  case 2:
    console.log("Tuesday");
    break;
  case 3:
    console.log("Wednesday");
    break;
  default:
    console.log("Another day");
}

Output

Wednesday

break and fall-through

Without break, execution falls through into the next case. That is occasionally useful for grouping cases, but forgetting break is a common bug:

Example 2Try it yourself
function kind(day) {
  switch (day) {
    case "Sat":
    case "Sun":
      return "weekend";
    default:
      return "weekday";
  }
}
console.log(kind("Sun"), kind("Tue"));

Output

weekend weekday

An object lookup alternative

For simple value-to-value mappings, an object is often clearer than a switch:

Example 3Try it yourself
const httpStatus = { 200: "OK", 404: "Not Found", 500: "Server Error" };
const code = 404;
console.log(httpStatus[code] ?? "Unknown");

Output

Not Found

Test yourself

Which comparison does switch use to match cases?

  1. == (loose equality)
  2. === (strict equality)
  3. Object.is only
  4. > and <
Show answer

Answer: === (strict equality)