Switch Groups Cases Through Deliberate Fall Through
switch compares with strict equality so a string status never hits a number case, and deliberately omitted breaks group neighboring cases into one branch.
Code
function describeResponse(status) {
let bucket;
switch (true) {
case status >= 500:
bucket = 'server error';
break;
case status >= 400:
bucket = 'client error';
break;
case status >= 300:
bucket = 'redirect';
break;
default:
bucket = 'success';
}
return bucket;
}
// 有意省略 break:多个 case 共享同一段代码(fall-through 分组)
function sizeClass(size) {
let label;
switch (size) {
case 0:
label = 'empty';
break;
case 1:
case 2:
case 3:
label = 'small';
break;
case 4:
case 5:
label = 'medium';
break;
default:
label = 'large';
}
return label;
}
for (const status of [200, 302, 404, 503]) {
console.log(status, '->', describeResponse(status));
}
for (const size of [0, 2, 5, 9]) {
console.log(size, '->', sizeClass(size));
}
// switch 是严格比较:字符串 '2' 不会命中 case 2
let result = 'no match';
switch ('2') {
case 2:
result = 'matched number';
break;
}
console.log("'2' vs case 2:", result);Output
Captured from a sandboxed run of this snippet in the build pipeline.
200 -> success
302 -> redirect
404 -> client error
503 -> server error
0 -> empty
2 -> small
5 -> medium
9 -> large
'2' vs case 2: no matchHow the snippet works
Switch Groups Cases Through Deliberate Fall Through comes down to the functions describeResponse and sizeClass.
Two loops stack here: for (const status of [200, 302, 404, 503]) selects, for (const size of [0, 2, 5, 9]) processes.
Caveats
- No package installation, no environment variables, no setup steps.
Using it
Entry signature: function describeResponse(status)
Key statements
result = 'matched number';
bucket = 'server error';
bucket = 'client error';
Interactive Tools for This Topic
FAQ
- Do I need to install anything before running this?
- No — every API used here ships with the language runtime, so there is nothing to install. The file defines `describeResponse`, `sizeClass` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.