Greg's Blog

helping me remember what I figure out

Switch/case Statements in Cfscript

| Comments

Just recently I have been moving away from using the tag based development methodology of ColdFusion and been doing most of my coding using cfscript. Of course this doesn’t natively give me access to the wealth of functionality that ColdFusion has [note: there are ways around that and I hope I’ll be bale to write something up soon], however it does give you a more traditional feel for coding and can certainly be a bit tighter. Here I just wanted to highlight how <cfswitch> and <cfcase> differ slightly when used as swicth/case in <cfscript>

OK let’s take a look at the code traditional CF style side by side with cfscript stylee:

<cfswitch expression=”#yourExpression#”>
<cfcase value=”a,b,c”>
…something…
</cfcase>
<cfcase value=”d”>
…something else…
</cfcase>
<cfdefaultcase>
… default behaviour goes here …
</cfdefaultcase>
</cfswitch>

<cfscript>
switch(yourExpression) {
case “a”: case “b”: case “c”:
…something…
break;
case “d”:
…something else…
break;
default:
… default behaviour goes here …
break;
}
</cfscript>

I guess that side by side the comparison in terms of neatness and tightness does not really shine through. However this is just for swicth/case, once you come to work with cfscript you’ll truly appreciate the scripting approach. So what differs:

  1. The first thing is that you will need to include a break; statement for each case. Failure to do that will result in the call processing the entire switch until either reaches the end or encounters a break;
  2. Multiple cases on one line need to listed individually (case “a”: case “b”: etc…) as opposed to a comma delimited list in cfcase (value=”a,b,etc…”)
  3. The default case in cfscript is declared using default: (and don’t forget the break;)

And that’s about it. A useful reference hopefully.

Comments