My first `case` statement in 60 months.

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[1] 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 @

@ at the corner of each section and then turn off the appropriate borders to give it the look he wanted. I had named each @

@ 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

    case 'b':
      // set bottom location, turn off top border
  // 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

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

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.

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

Leave a Reply

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