ScanSkill

switch

The switch statement evaluates the given expression, if the value of the case matches that of the expression the case block is executed.

Syntax

switch (expression) {
  case value1:
    //Statements that are needed to be executed
    [break;]
  case value2:
    [break;]
  ...
  case valueN:
    [break;]
  [default:
    //Statements executed when none of
    [break;]]
}

Example

const day = "1";

switch (day) {
  case "1":
    console.log("sunday");
    break;
  case "2":
    console.log("Monday");
    break;
  case "3":
    console.log("tuesday");
    break;
  case "4":
    console.log("wednesday");
    break;
  case "5":
    console.log("thrursday");
    break;
  case "6":
    console.log("friday");
    break;
  case "7":
    console.log("saturday");
    break;
  default:
    console.log("Only from 1 to 7");
    break;
}
// Prints: sunday

The switch statement takes in an expression, it checks for the value given in the expression in the case values. If it is found then the case block associated with that value is run. Otherwise, it goes to the default statement.