Home

Switch cases falling through

#learning #javascript

29th of June 2021


I’ve learned something that was interesting to me. This might be something basic, but it felt counterintuitive to me and at a glance, since I saw no issue with this code:

switch (variant) {
 case 'foo' || 'bar' :
 doSomething();
 break;

 case ...  
}

So if we imagine we have multiple cases covering multiple scenarios, I would understand this as if the variant is ‘foo’ or ‘bar’, doSomething(). I, however, would be (and was) wrong.

Multi-criteria cases are handled inside the switch statement in a very defined way. In our case above, only the first condition would ever be checked, so the second (and any subsequent cases) would fall through.

The correct way is to move each condition in its own case and make use of a break. Or to be more precise, the lack of break. If one case does not contain it, we do not escape the switch statement, but continue on to check if any additional cases might return a match. We simply chain multiple cases, grouped together. So refactored code from above would turn into:

switch (variant) {
 case 'foo':
 case 'bar':
 doSomething();
 break;

 case ...  
}

Sources: