Javascript switch

2010-07-24

The switch statement is a well known mechanism in coding terms. Still, there seems to be one edge case which needs a little attention. The edge case being the default clause.

A switch is meant to replace a long series of if statements. It has the additional property of being able to fall through and defining a case that should be executed if all others fail to match.

Switches in Javascript use strict type checking (===). So you never have to worry about coercion, which prevents a few wtfjs :). If on the other hand you were counting on coercion, tough luck because you can't force it.

The argument of switch nor the cases are required to be of any specific type. Note that due to strict type matching the argument can only match a case if it is of the same type.

A typical switch will look something like this:

Code: (Javascript)
switch (x) {
case 5:
alert(5);
break;
case 6:
alert(6);
break;
default:
alert("unknown: "+x);
}

Note that the break statements are not required, but they are desired because otherwise you would get three alerts if x===5.

Code: (Javascript)
switch (x) {
case 5: alert(5);
case 6: alert(6+" (or maybe 5?)");
default: alert("unknown: "+x+" (or maybe 5? or 6?)");
}

As you can see in this example, the cases fall through. You can only prevent this by a break or return statement. The break statement will make Javascript continue after the switch. The return statement immediately returns from the current function (as it normally would).

You probably knew all that though (except perhaps for the strict type checking ;)). But did you know that the default clause does not have to be at the end of the clause list?

Code: (Javascript)
switch (x) {
case 5:
alert(5);
break;
default:
alert("unknown: "+x);
break;
case 6:
alert(6);
break;
}

Now what happens if x===6? Will it go to the default case because that's found before the case for 6? No. It will first visit ALL cases before moving to the default clause. But note that it will be able to fall through after that! This is the exact reason default is allowed anywhere.

Code: (Javascript)
switch (x) {
case 5:
alert(5);
default:
alert("unknown: "+x);
case 6:
alert(6);
}

In this example, two alerts are shown if x is not 5 or 6.

Note that it's generally accepted to be a "best practice" never to fall through. Any time you would "need" fall through, there's a different pattern that would fix it equally as well, probably better. The reason you should prevent falling through is that it can lead to bugs in your code which are very hard to find. You have been warned :)

Hope it helps :)