The comma operator (,
) evaluates its operands, from left to right, and returns the second one. That’s useful in some situations, but
just wrong in a switch
case
. You may think you’re compactly handling multiple values in the case, but only the last one in
the comma-list will ever be handled. The rest will fall through to the default.
Similarly the logical OR operator (||
) will not work in a switch
case
, only the first argument will be
considered at execution time.
Noncompliant Code Example
switch (a) {
case 1,2: // Noncompliant; only 2 is ever handled by this case
doTheThing(a);
case 3 || 4: // Noncompliant; only '3' is handled
doThatThing(a);
case 5:
doTheOtherThing(a);
default:
console.log('Neener, neener!'); // this happens when a==1 or a == 4
}
Compliant Solution
switch (a) {
case 1:
case 2:
doTheThing(a);
case 3:
case 4:
doThatThing(a);
case 5:
doTheOtherThing(a);
default:
console.log('Neener, neener!');
}
Exceptions
The switch (true)
pattern is a common programming practice to match against expressions rather than literals. Expressions in the
case
clauses act as guards, i.e., they must evaluate to true
if the execution is to continue in the branch.
function weekStatus (day) {
let status;
switch (true) {
case (day === 'MON' || day === 'TUE' || day === 'WED' || day === 'THU' || day === 'FRI'):
status = 'Weekday';
break;
case (day === 'SAT' || day === 'SUN'):
status = 'Weekend';
break;
}
return status;
}