Smarter Switch Statements

Recently, a coworker showed me a development script from Apple and we both took an interest in how the web developers used switch statements for the script he had found.

Traditionally, switches have been used in place of simple (yet lengthy) if/else blocks, because a switch will lay your logic steps in a way that is easier to use than a lengthy if/else block. If you’re unfamiliar with switch blocks then take a look at the W3C JavaScript switch statement page and a switching example I put together with JSfiddle.

Now for an example of what I’m referring to as “Smart switching”. I call this smart switching because it accomplishes everything an if/else does and also allows the pairing of cases by allowing you to choose where you want to insert case breaks.

Basic example of “Smart switching” :

{syntaxhighlighter brush: jscript;fontsize: 100; first-line: 1; }var num = 7;

/**
* you always use “switch(true)” — “Smart swithing” you do your logic
* in the case instead.
*/
switch(true) {
case num % 2 == 0:
document.write(num + ” is an even number.<br />”);
break;
case num % 2 == 1:
document.write(num + ” is an odd number.<br />”);
break;
}

switch(true) {
case num > 10:
document.write(num + ” is > 10.<br />”);
break;
case num > 5:
document.write(num + ” is > 5.<br />”);
break;
case num > 0:
document.write(num + ” is > 0.<br />”);
break;
}{/syntaxhighlighter}

 

 

If you’re anything like me, you have already planned to replace your complex if/else statements with this “smart switches”.

Leave a comment

Your email address will not be published. Required fields are marked *