Today’s fun JavaScript trick: switch(true)
Programmers who are new to JavaScript but familiar with other C-syntax languages like C or Java are definitely familiar with the switch statement, but may not be aware of how much more flexible this construct is in JavaScript. In fact, I’ve heard experienced programmers claim that they never use switch statements!
One major difference in the JavaScript switch statement is the fact that the condition can be any type of variable, not just numeric types. Most obviously, this allows you to use a string or an object, which provides a lot of flexibility. So much flexibility, in fact, that when used with a boolean condition the JavaScript switch can provide a very different type of program flow control.
For example, consider a case where we want to take different actions, respectively, if a number is greater than 100, less than -100, or equal to 0. We could write it as a series of if/else ifs, like this:
if(x > 100) {
doSomething();
} else if (x < -100){
doSomethingElse();
} else if (x == 0){
doAThirdThing();
}
Using a switch statement, this block becomes:
switch(true){
case (x > 100):
doSomething();
break;
case (x < -100):
doSomethingElse();
break;
case (x == 0):
doAThirdThing();
break;
}
Is that any better? Probably not. In fact, it’s a little more clever, which may make it a little harder for other programmers to maintain, which would actually make it worse. However, consider the case where we want to take a specific action if x is greater than 100 or y is greater than 200, or z is less than -100, or if (x + y + z) is greater than 500. We could write this:
if(x>100 || y > 200 || z < -100 || (x + y + z) > 500){
// um, what?
doSomething();
}
Using the switch statement, that same code looks like this:
switch(true){
case x > 100:
case y > 200:
case z < -100:
case (x + y + z) > 200:
doSomething();
break;
}
I find the second block much more readable. Is it groundbreaking or radically new? No, but this is just another case where the flexibility of JavaScript’s syntax provides an interesting opportunity for more maintainable, readable code.