javascript switch() or if()

99封情书 提交于 2020-01-28 02:29:23

问题


which would be better if i do this:

if(message == 'redirect')
{
    is_valid.accepted = true;
}
else if(message == 'invalid id')
{
    is_valid.accepted = false;
}
else
{
    is_valid.accepted = false;
}

or i do it this way

switch (message)
{
case 'invalid id':
default:
    is_valid.accepted = false;
    break;
case 'redirect':
    is_valid.accepted = true;
    break;
}

回答1:


You might use switch if you foresaw needing to add lots of new cases.

If you won't be adding many new cases, I might do, for clarity:

is_valid.accepted = message=='redirect';

(also note that your check for 'invalid id' does nothing)

Nevertheless if you had to add new things, notice how it's good you don't have to repeat yourself don't have to repeat yourself don't have to repeat yourself, also the sexy formatting:

switch (message)
{
    case 'invalid id':
    case 'penguin invasion':
    case 'the internet is down':
    case 'error not enough caffeine':
        is_valid.accepted = false;
        break;

    case 'redirect':
    case 'upvote me':
    case 'vip':
    case 'flamewar':
        is_valid.accepted = true;
        break;

    default:
        is_valid.accepted = false;
        // perhaps log or something
}

Imagine all those ugly else and else-ifs you'd have otherwise.


sidenote: If you had really complicated rules, but still a whitelist-blacklist-on-a-single-flag paradigm, then:

var blacklist = ['invalid id', 'penguin invasion', 'the internet is down' 'error not enough caffeine'];
var whitelist = ['redirect', 'upvote me', 'vip', 'flamewar'];

is_valid.accepted = whitelist.indexOf(message)!=-1;

You might also do this if you wanted to dynamically construct your whitelist.




回答2:


It depends on your definition of better. Do you want it to be a better reading experience or better performance?

I always jsPerf things. I don't really care much about readability if it makes my code faster/proper.

Here is a jsPerf of a bunch of different switch vs. if/else if/if ==/if === statements.

http://jsperf.com/switch-if-else/16

This is revision 16 of the test. So if you are looking at this 10 weeks from now make sure you scroll to the bottom and grab the most recent test.




回答3:


The switch statement is more efficient/expressive than if/else in some cases. While the following if/else statement

let x = 123;

if (x) {/*...*/} // implicit type casting (to boolean)
else {/*...*/}

can be easily converted to:

switch (!!x) { // explicit type casting (to boolean)
  case true: /*...*/ break;
  default: /*...*/
}

this switch statement on the other hand

function algo(x) {/*...performing a complex algorithm...*/}

switch (algo(123)) { // executed once
  case "result 1": /*...*/ break;
  case "result 2": /*...*/ break;
  case "result 3": /*...*/ break;
  default: /*...*/
}

results in an incredible inefficient if/else statement (switch is more efficient):

if (algo(123) === "result 1") {/*...*/}
else if (algo(123) === "result 2") {/*...*/}
else if (algo(123) === "result 3") {/*...*/}
else {/*...*/}

or requires an if/else with additional variable, which is declared for this purpose exclusively:

let y = algo(x); // additional variable

if (y === "result 1") {/*...*/}
else if (y === "result 2") {/*...*/}
else if (y === "result 3") {/*...*/}
else {/*...*/}

Please note that additional elements (like variables) cause more complexity and complexity makes programs more error prone. The switch statement doesn't need such a variable, because it is more expressive.




回答4:


Switch is better if you're working with a long list of possible conditions on the same variable. In this case, I don't think there's much reason to use switch() unless you prefer the syntax.




回答5:


If you go with the if statement, I personally prefer setting default values above the if, like this:

is_valid.accepted = false;
if(message == 'redirect')
{
    is_valid.accepted = true;
}

That way, you always default to a safe behavior that is less likely to break if you add more options later on. Also, you see the default behavior at a glance without having to read through the if-then-else logic. And it's much shorter code.




回答6:


Ternary? is_valid.accepted = (message !== 'invalid id') ? true : false;



来源:https://stackoverflow.com/questions/5711347/javascript-switch-or-if

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!