Question

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 ColdFusion 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?

Was it helpful?

Solution

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

OTHER TIPS

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 ) />
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top