How to use the Switch Statement in Javascript?

About

This page is about the switch statement in Javascript

General Rules

  • If you omit a break from a case, and that case matches or runs, execution will continue with the next case.
  • Always create a block after each case to create a block scope and avoid leaking variable (You will also avoid the eslint warning: ESLint: Unexpected lexical declaration in case block.(no-case-declarations))

Example:

switch (x){
  case 1: { // <-- start of the case block
    ....
    break;
  } // <-- end of the case block
}

Example

Without a break

color = "green"
switch (color) { 
    case "blue": {
         console.log("blue");
    }
    case "green": { 
          console.log("green");
    }
    case "red": {
         console.log("red");
    }
    default: {
         console.log("default");
    }
}

With break

color = "green"
switch (color) { 
    case "blue": {
         console.log("blue");
         break;
    }
    case "green": {
          console.log("green");
          break;
    }
    case "red": {
          console.log("red");
          break;
    }
    default: {
         console.log("default");
    }
}





Discover More
Javascript - Flow (Control Structures)

Flow / Conditional expression in Javascript in Javascript See loop JavaScript_basics



Share this page:
Follow us:
Task Runner