[javascript] Is returning out of a switch statement considered a better practice than using break?

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?

This question is related to javascript return switch-statement break

The answer is


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.


Neither, because both are quite verbose for a very simple task. You can just do:

let result = ({
  1: 'One',
  2: 'Two',
  3: 'Three'
})[opt] ?? 'Default'    // opt can be 1, 2, 3 or anything (default)

This, of course, also works with strings, a mix of both or without a default case:

let result = ({
  'first': 'One',
  'second': 'Two',
  3: 'Three'
})[opt]                // opt can be 'first', 'second' or 3

Explanation:

It works by creating an object where the options/cases are the keys and the results are the values. By putting the option into the brackets you access the value of the key that matches the expression via the bracket notation.

This returns undefined if the expression inside the brackets is not a valid key. We can detect this undefined-case by using the nullish coalescing operator ?? and return a default value.

Example:

_x000D_
_x000D_
console.log('Using a valid case:', ({
  1: 'One',
  2: 'Two',
  3: 'Three'
})[1] ?? 'Default')

console.log('Using an invalid case/defaulting:', ({
  1: 'One',
  2: 'Two',
  3: 'Three'
})[7] ?? 'Default')
_x000D_
.as-console-wrapper {max-height: 100% !important;top: 0;}
_x000D_
_x000D_
_x000D_


It depends, if your function only consists of the switch statement, then I think that its fine. However, if you want to perform any other operations within that function, its probably not a great idea. You also may have to consider your requirements right now versus in the future. If you want to change your function from option one to option two, more refactoring will be needed.

However, given that within if/else statements it is best practice to do the following:

var foo = "bar";

if(foo == "bar") {
    return 0;
}
else {
    return 100;
}

Based on this, the argument could be made that option one is better practice.

In short, there's no clear answer, so as long as your code adheres to a consistent, readable, maintainable standard - that is to say don't mix and match options one and two throughout your application, that is the best practice you should be following.


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to return

Method Call Chaining; returning a pointer vs a reference? How does Python return multiple values from a function? Return multiple values from a function in swift Python Function to test ping Returning string from C function "Missing return statement" within if / for / while Difference between return 1, return 0, return -1 and exit? C# compiler error: "not all code paths return a value" How to return a struct from a function in C++? Print raw string from variable? (not getting the answers)

Examples related to switch-statement

Switch in Laravel 5 - Blade Switch case: can I use a range instead of a one number SQL use CASE statement in WHERE IN clause SSRS Conditional Formatting Switch or IIF Switch statement equivalent in Windows batch file OR operator in switch-case? Regarding Java switch statements - using return and omitting breaks in each case Using two values for one switch case statement C# how to use enum with switch Switch statement multiple cases in JavaScript

Examples related to break

How to break a while loop from an if condition inside the while loop? illegal use of break statement; javascript How can I use break or continue within for loop in Twig template? break statement in "if else" - java Regarding Java switch statements - using return and omitting breaks in each case Is it bad practice to use break to exit a loop in Java? break/exit script Breaking out of a for loop in Java How to break out of while loop in Python? How to kill a while loop with a keystroke?