views:

511

answers:

2

In JavaScript, you can do this:

var a = null;
var b = "I'm a value";
var c = null;
var result = a || b || c;

And 'result' will get the value of 'b' because JavaScript short-circuits the 'or' operator.

I want a one-line idiom to do this in ColfFusion and the best I can come up with is:

<cfif LEN(c) GT 0><cfset result=c></cfif>
<cfif LEN(b) GT 0><cfset result=b></cfif>
<cfif LEN(a) GT 0><cfset result=a></cfif>

Can anyone do any better than this?

+7  A: 

ColdFusion doesn't have nulls.

Your example is basing the choice on which item is an empty string.

If that is what you're after, and all your other values are simple values, you can do this:

<cfset result = ListFirst( "#a#,#b#,#c#" )/>

(Which works because the standard list functions ignore empty elements.)

Peter Boughton
Thanks Peter. Be sure to use a different delimeter if the values in question could contain commas.
Brendan Kidwell
A good point. In the past I've used Chr(65535) for this purpose, since it is not a real character but does actually work as a delimiter.
Peter Boughton
Also, to deal with complex variables if checking against empty string, you could adapt the function in my other answer - just change the `NOT isNull` to be `NOT (isSimpleValue(Arguments[i]) AND Arguments[i] EQ '')`
Peter Boughton
+1  A: 

Note: other CFML engines do support nulls.

If we really are dealing with nulls (and not empty strings), here is a function that will work for Railo and OpenBlueDragon:

<cffunction name="FirstNotNull" returntype="any" output="false">
 <cfset var i = 0/>
 <cfloop index="i" from="1" to="#ArrayLen(Arguments)#">
  <cfif NOT isNull(Arguments[i]) >
   <cfreturn Arguments[i] />
  </cfif>
 </cfloop>
</cffunction>

Then to use the function is as simple as:

<cfset result = FirstNotNull( a , b , c ) />
Peter Boughton