My first `case` statement in 60 months.

It's been a long time since I've had the chance to use a 'case' statement. It turns out that I've missed them.
The first time flipping through my O'Reilly Javascript Definitive Guide, I was pleasantly surprised to read that Javascript had a case statement. I'm not sure why I was surprised, but I guess I forgot about it considering that I have been programming in Perl* and Python for so long.

The other day, I came across a case statement while glancing through some Javascript code from another company. This time I made a mental note to use it the next time that I could.

Well, my chance arrived yesterday while doing a project for work. Our designer had wanted to place bounding corners at certain sections on the page. I was going to position a <div> at the corner of each section and then turn off the appropriate borders to give it the look he wanted. I had named each <div> corner using a suffix which described its location (eg, tl - top left) and wanted to think of a way to map that name to the borders which were to be showing.

Here is the incomplete code using a case statement. I think it is more concise and easier to read than if it had been written using if statements.

My First Javascript Case Statement:

this.corner_suffix = ['tl','tr','br','bl'];

for( i = 0; i < this.corner_suffix.length; i++ ) {

  // the first character takes care of top/bottom borders
  switch ( this.corner_suffix[i].charAt(0) ) {
    case 't':
      // set top location, turn off bottom border
      break;

    case 'b':
      // set bottom location, turn off top border
      break;
  }
  // the second character takes care of left/right borders
  switch ( this.corner_suffix[i].charAt(1) ) {
    case 'r':
      // set right location, turn off left border
      break;

    case 'l':
      // set left location, turn off right border
      break;
    }
}


I was happy to have rediscovered the case statement and found that it was very natural to write it once I had remembered the rules for break and default. It's like meeting an old friend: you get along instantly and continue without missing a beat.

* I stopped programming in Perl sometime in 2002. I see that there is now a module called Switch which emulates a case construct, released sometime in 2002.