DEV Community

loading...

The Auto-breaking Switch Statement: A Proposal

Meghan (she/her)
24. Local trans witch who prefers to do magic with a keyboard. she/her. Currently hacking away at making the Web less centralized.
・1 min read

I have taken advantage of fallthoughs in switch statements maybe twice. And that's a hard maybe. I can only really remember one instance where I did not break after every case block. For most of us, a switch statement will be mostly used as a super compact if...else statement like the following:

function getSeasonFromMonth(month)
{
    let season = null;
    switch (month)
    {
        case December:
        case January:
        case February: {
            season = Winter;
            break;
        }
        case March:
        case April:
        case May: {
            season = Spring;
            break;
        }
        case June:
        case July:
        case August: {
            season = Summer;
            break;
        }
        case September:
        case October:
        case November: {
            season = Autumn;
            break;
        }
    }
    return season;
}
Enter fullscreen mode Exit fullscreen mode

While you would probably use return in this case, I'm not to get the point across. What if, if you put a break in front of the switch then it automatically breakd after every block? So you could rewrite the above as:

function getSeasonFromMonth(month)
{
    let season = null;
    switch (month)
    {
        case 'December':
        case 'January':
        case 'February': {
            season = 'Winter';
        }
        case 'March':
        case 'April':
        case 'May': {
            season = 'Spring';
        }
        case 'June':
        case 'July':
        case 'August': {
            season = 'Summer';
        }
        case 'September':
        case 'October':
        case 'November': {
            season = 'Autumn';
        }
    }
    return season;
}
Enter fullscreen mode Exit fullscreen mode

Clean code doesn't repeat itself and I can only imagine the nightmares caused from the side-effects of a forgotten break.

~So give us a break TC39 and put this in!~

Discussion (1)

Collapse
nektro profile image
Meghan (she/her) Author

While I do realize this could be polyfill'd (since I have before) using functions for code blocks adds a bunch of unnecessary scopes and makes code optimization far harder.