Case & Break

Controlling switch flow.

Examples

With Break

Standard usage with break.

let text;
switch ("A") {
  case "A":
    text = "Correct!";
    break;
  case "B":
    text = "Wrong!";
    break;
}
console.log(text); // Correct!

Fallthrough (No Break)

What happens when you forget break (sometimes useful).

let text;
switch ("A") {
  case "A":
    text = "Part A ";
    // No break
  case "B":
    text += "Part B";
}
console.log(text); // Part A Part B

Grouping Cases

Multiple cases sharing the same code block.

let text;
switch (val) {
  case "A":
  case "B":
  case "C":
    text = "Passing Grade";
    break;
  case "D":
    text = "Failing Grade";
}

Test Your Knowledge

JavaScript Quiz

No quiz available for this topic yet.