Condition

Switch

JavaScript

 

Switch

ECMAScript 5
var status = 1;

switch (status) {
  case 0:
      console.log("Ready");
      break;
  case 1:
      console.log("Running");
      break;
  case 2:
      console.log("Done");
      break;
  default:
      console.log("Out of service");
}

If you end up using a lot of else if for equality conditions, then it is probably better to re-write your conditions in switch block.

The default section runs when none of the condition cases met.

The break keyword, exits out of the switch block. This is necessary to be used, otherwise the execution continues to the next case, no matter if that case condition is met or not.

This will print Running on Console.

 

Fallthrough

ECMAScript 5
var status = 1;

switch (status) {
  case 0:
      console.log("Ready");
      break;
  case 1:
  case 2:
      console.log("Running or Done");
      break;
  default:
      console.log("Out of service");
}

You can mix 2 cases by not mentioning break.

Here if the status is 1 or 2, it will print Running or Done on Console.