JavaScript:JavaScript Switch Statement and Multiple Case Handling
JavaScript•Switch Statement

JavaScript Switch Statement and Multiple Case Handling

The switch expression is evaluated once and compared against case clauses using strict equality (===).

Syntax

switch (expression) { case value1: // code break; default: // fallback }

Parameters & Values

Key components and acceptable values for this structure:

ParameterTypeDescription
caseClauseMatched using strict === comparison.
breakStatementPrevents fallthrough execution into subsequent cases.

Ready-to-Run Code Example

Executable in Compilra

Run this complete, working example directly without installing JavaScript locally:

// JavaScript Switch Statement
const httpMethod = "POST";
let actionDescription;

switch (httpMethod) {
  case "GET":
    actionDescription = "Retrieving requested data";
    break;
  case "POST":
  case "PUT":
    actionDescription = "Mutating / saving server resource";
    break;
  case "DELETE":
    actionDescription = "Destroying record from storage";
    break;
  default:
    actionDescription = "Unsupported HTTP verb: " + httpMethod;
}

console.log("HTTP Method:", httpMethod);
console.log("Action:     ", actionDescription);
Expected Output:
HTTP Method: POST
Action:      Mutating / saving server resource

How It Works: Step-by-Step

  • Lines 5-16: Evaluates httpMethod against cases with explicit break statements.
  • Lines 9-10: Groups POST and PUT together into a single combined handler.

Key Concepts

  • switch uses strict equality (===) when matching case values.
  • Omitting break causes execution to fall through into the next case automatically.
  • The default clause handles any unmatched values.

Common Mistake: Forgetting the break statement leading to unintended fallthrough

Without break, code cascades down into next cases even if their conditions do not match.

❌ Incorrect
case 1: doA(); case 2: doB(); // Both doA and doB will execute!
✅ Correct
case 1: doA(); break; case 2: doB(); break;

Related JavaScript Tutorials & Compiler

Run and test JavaScript on Compilra

Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.

JavaScript Online Compiler