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 @
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.
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.