Javascript - Statement switch Statement

Introduction

The syntax for the switch statement in ECMAScript is as follows:

switch (expression)  {
  case value: statement
    break;
  case value: statement
    break;
  case value: statement
    break;
  case value: statement
    break;
  default: statement
}

If the expression is equal to the value, execute the statement for that case.

The break keyword causes code execution to jump out of the switch statement.

Without the break keyword, code execution falls through the original case into the following one.

The default keyword indicates what is to run if the expression does not evaluate to one of the cases.

Consider the following code:

if (i == 25){
  console.log("25");
} else if (i == 35) {
  console.log("35");
} else if (i == 45) {
  console.log("45");
} else {
  console.log("Other");
}

The equivalent switch statement is as follows:

switch (i) {
    case 25:
        console.log("25");
        break;
    case 35:
        console.log("35");
        break;
    case 45:
        console.log("45");
        break;
    default:
        console.log("Other");
}

Related Topics

Exercise