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

后端 未结 3 1925
太阳男子
太阳男子 2021-01-29 20:37

Option 1 - switch using return:

function myFunction(opt) 
{
    switch (opt) 
    {
        case 1: retur         


        
相关标签:
3条回答
  • 2021-01-29 21:22

    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.

    0 讨论(0)
  • 2021-01-29 21:27

    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.

    0 讨论(0)
  • 2021-01-29 21:28

    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:

    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')
    .as-console-wrapper {max-height: 100% !important;top: 0;}

    0 讨论(0)
提交回复
热议问题