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

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

Option 1 - switch using return:

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


        
3条回答
  •  醉梦人生
    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.

提交回复
热议问题