DEV Community

Discussion on: If (all) else is complicated, switch to switch?

Collapse
 
andrewbridge profile image
Andrew Bridge

Switches have the potential to be super powerful, the ability to let conditions fall through...

switch(state) {
    case 'foo':
        console.log('one');
    case 'bar':
        console.log('two');
        break;
    default:
        console.log('three');
}

// When state === 'foo', 'one' and 'two' are logged
Enter fullscreen mode Exit fullscreen mode

...means there are some complex logical flows that could achieved.

But the hidden complexity fall-through case statements add and the ease of missing them means it's far more likely you'll introduce hard to find bugs or regressions.

As a result, most coding styles either warn or actively disallow case statements without a break; statement at the end. Removing that ability removes the key differentiator of a switch statement and makes it a slightly more concise if..else if statement assuming you have a set of conditions checking the same variable for different values. Pretty niche!