Javascript - Switch Statement

> (World Wide) Web - (W3|WWW) > Javascript (Js|ECMAScript) > ECMAScript - Grammar Standard

1 - About

The switch statement has fall through behavior therefore the break is important.

3 - Example

If you omit break from a case, and that case matches or runs, execution will continue with the next case.

  • Without breal
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");
}

Advertising
web/javascript/es/switch.txt · Last modified: 2019/02/16 17:40 by gerardnico