DEV Community

Meghan (she/her)
Meghan (she/her)

Posted on

2

The Auto-breaking Switch Statement: A Proposal

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!~

Image of Datadog

The Essential Toolkit for Front-end Developers

Take a user-centric approach to front-end monitoring that evolves alongside increasingly complex frameworks and single-page applications.

Get The Kit

Top comments (1)

Collapse
 
nektro profile image
Meghan (she/her)

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.

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay