Sunday, 11 October 2009

A Neat Trick using Switch in JavaScript

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.

2 comments:

Pete said...

I like using dictionaries of functions for this, like:
var decisions = {
foo: function() { alert('foo'); },
bar: function() { alert('bar'); }
};
decision['bar'](); // spits up bar

This way, they can be modified at runtime if required, by just adding to the decisions map

Dylan Beattie said...

Very nice. I love how expressive Javascript is at doing this kind of thing (and I wish JScript.NET wasn't such an undocumented outcast in the .NET ecosystem!)

Still, with LINQ and the dynamic keyword, another 2-3 years and C# might actually catch up with Netscape-era Javascript.