This is the first post of a hopeful series dubbed “JavaScript, tip of the week“; I will try to release a tip in some form every week.

I’m young and haven’t been doing this programming thing for very long so the fact that I’ve never had to use a switch-case statement (to my recollection) might not be very impressive; actually you probably see this as a bad thing and you might even be wondering why I haven’t. I can’t really explain why but I seem to have an inherent dislike of things like this:

switch (something) {
 
    case 1:
        doX();
    break;
 
    case 2:
        doY();
    break;
 
    case 3:
        doN();
    break;
 
    // And so on...
 
}

The fictional author of this code obviously doesn’t know enough about JavaScript to make use of its various other constructs, most of them ten times more suited to this situation than an ugly switch statement. It’s not its appearance that truly annoys me though; it’s the knowledge that there are so many easier and more graceful ways of achieving such functionality.

Switch statements are considered as useful when you have a single variable and dependent on its value you want to carry out one of a number of different tasks. Using multiple if-else clauses doesn’t seem appropriate so the switch statement is often called upon to lend a hand. I’m sure most of you are familier with it and have seen it more than once before.

Let’s take the example from above; dependent on the value of something we run doX, doY or doN. In JavaScript, the same logic can be expressed with a simple lookup table in the form of an object:

var cases = {
    1: doX,
    2: doY,
    3: doN
};
if (cases[something]) {
    cases[something]();
}

Not only is this cleaner but it’s also reusable, modifiable and accessible… All the conditions are saved as part of an object, so if you ever need to recall or change those conditions then it’s as easy as cases[condition].

I suspect this covers about 90% of situations where a switch-statement is used; the remaining 10% are probably legitimate uses. Using a lookup table as an alternative to the Switch statement is not new; in fact this is the only way such logic can be expressed in both the Python and Lua languages, both of which have no support for switch statements.

So, my message is the following: do not use switch-case constructs unless absolutely necessary. Why? – Because there are better alternatives; simple as that!

Read more about the “Switch Statement” here: en.wikipedia.org/wiki/Switch_statement.

Thanks for reading! Please share your thoughts with me on Twitter. Have a great day!