A Neat Trick using Switch in JavaScript
Posted by Dylan Beattie on 11 October 2009 • permalink You ever see code blocks that look like this?if (someCondition) { doSomeThing(); } else if (someOtherCondition) { doSomeOtherThing(); } else if (someThirdCondition) { doSomeThirdThing(); } else { doUsualThing(); }
Turns out in Javascript - and, I suspect, in other dynamically-typed languages that support switch statements - that you can do this:
switch(true) { case someCondition: doSomeThing(); break; case someOtherCondition: doSomeOtherThing(); break; case someThirdCondition: doSomeThirdThing(); break; default: doUsualThing(); break; }
Of course, by omitting the break keyword you could wreak all sorts of havoc – but I can think of a couple of scenarios where you want to apply one or more enhancements (e.g. adding one or more CSS classes to a piece of mark-up) and this would fit very nicely.