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:
| Parameter | Type | Description |
|---|---|---|
| case | Clause | Matched using strict === comparison. |
| break | Statement | Prevents fallthrough execution into subsequent cases. |
Ready-to-Run Code Example
Executable in CompilraRun 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
JavaScript If...Else, Ternary Operator, and Branching
Control code execution based on conditions using if, else if, else, and ternary expressions.
JavaScript For Loops, for...of, and for...in Iteration
Master classical for loops, for...of for iterable items, and for...in for object properties.
JavaScript Functions: Arrow Functions, Parameters, and Rest
Master function declarations, expressions, arrow functions, and rest parameters (...args).
JavaScript Online Compiler
Open in Compilra IDE
Run and test JavaScript on Compilra
Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.