In JavaScript, is returning out of a switch statement considered a better practice than using break?

Code Maverick picture Code Maverick · May 24, 2011 · Viewed 143.8k times · Source

Option 1 - switch using return:

function myFunction(opt) 
{
    switch (opt) 
    {
        case 1: return "One";
        case 2: return "Two";
        case 3: return "Three";

        default: return "";
    }    
}

Option 2 - switch using break:

function myFunction(opt) 
{
    var retVal = "";

    switch (opt) 
    {
        case 1: 
            retVal = "One";
            break;

        case 2: 
            retVal = "Two";
            break;

        case 3: 
            retVal = "Three";
            break;
    }

    return retVal;
}

I know that both work, but is one more of a best practice? I tend to like Option 1 - switch using return best, as it's cleaner and simpler.


Here is a jsFiddle of my specific example using the technique mentioned in @ic3b3rg's comments:

var SFAIC = {};

SFAIC.common = 
{
    masterPages: 
    {
        cs: "CS_",
        cp: "CP_"
    },

    contentPages: 
    {
        cs: "CSContent_",
        cp: "CPContent_"    
    }
};

function getElementPrefix(page) 
{
    return (page in SFAIC.common.masterPages)
        ? SFAIC.common.masterPages[page]
        : (page in SFAIC.common.contentPages)
            ? SFAIC.common.contentPages[page]
            : undefined;
}

To call the function, I would do so in the following ways:

getElementPrefix(SFAIC.common.masterPages.cs);
getElementPrefix(SFAIC.common.masterPages.cp);
getElementPrefix(SFAIC.common.contentPages.cs);
getElementPrefix(SFAIC.common.contentPages.cp);

Problem here is that it always returns undefined. I'm guessing that it's because it's passing in the actual value of the object literal and not the property. What would I do to fix this using the technique described in @ic3b3rg's comments?

Answer

ic3b3rg picture ic3b3rg · May 24, 2011

A break will allow you continue processing in the function. Just returning out of the switch is fine if that's all you want to do in the function.