ianace ianace - 4 months ago 14
Javascript Question

javascript switch() or if()

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;
}

Answer

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.