switch statement

When needing to do a lot of comparisons for a single value, instead of using many if-else-if statements, you can use the switch statement:

const letter = "B-";
let gpa;

switch (letter) {
  case "A+":
  case "A":
    gpa = 4.0;
    break;
  case "A-":
    gpa = 3.7;
    break;
  case "B+":
    gpa = 3.3;
    break;
  case "B":
    gpa = 3.0;
    break;
  case "B-":
    gpa = 2.7;
    break;
  case "C+":
    gpa = 2.3;
    break;
  case "C":
    gpa = 2.0;
    break;
  case "C-":
    gpa = 1.7;
    break;
  case "D+":
    gpa = 1.3;
    break;
  case "D":
    gpa = 1.0;
    break;
  case "D-":
    gpa = 0.7;
    break;
  case "F":
    gpa = 0.0;
    break;
  default:
    gpa = null;
}

if (gpa !== null) { 
  console.log("Your GPA is " + gpa);
} else {
  console.error(letter + " cannot be converted to GPA value");
}
  • The default case in a switch statement is like the last else in an if-else-if chain. It will be reached if none of the previously tested conditions are true.

  • The break statement is needed to break out of the switch statement. In case you omit break, switch will run all the following cases until it encounters break or exits. This can be useful for grouping cases.

Keep in mind that JavaScript uses strict equality for switch statements.