Ternary Operator within ColdFusion 9

Posted: February 8, 2011 in ColdFusion

For the first time today I used ColdFusion’s new ternary operator. I learned about it last week as a alternative to the inline-IF (IIF()). No longer do I need to remember the quarks about the DE operator required in IIF.

A ternary operator takes three arguments: ((condition) ? trueStatement : falseStatement)

Example:

<tr class="#(currentrow mod 2) ? 'lightRow'  : 'darkRow'#">

This can also be done using inline if:

<tr class="#IIF(currentrow mod 2, DE('lightRow'), DE('darkRow')#">

Or using cfif:

<tr class="<cfif currentrow mod 2>lightRow<cfelse>darkRow</cfif>">

As you can see, you can use a simple inline operator without having to worry about IIF quirks or drawn out conditional statements. Remember this is introduced in ColdFusion 9.

Advertisements
Comments
  1. You don’t even need the ternary operator, you can just do:

    #(len(arguments.arg1))#

    Since CF treats positive numbers as a true value and zero as a false value it’ll work. If you want to be more explicit, you can use:

    #(len(arguments.arg1) gt 0)#

    This has worked in CF for as long as I can remember. It certainly works in CF6+ (but I think even in CF5.)

    • Chris says:

      Thanks for that great suggestion! I could have avoided a lot of headache if I would have just thought simplier. I’ll have to come up with another example for the Ternary.

      • Chris says:

        My previous example created some discussion on the efficiency of the code, so I updated the examples above.

  2. Tim says:

    thanks for this..really useful.

    however inside of a query param setting null=true if there is a length on your argument wouldn’t give the desired result as far as I understand it?

    eg: #(len(ARGUMENTS.arg1)# == true and would set the DB to NULL when it should have set the db

    so your second example really should be #(len(ARGUMENTS.arg1) EQ 0)#

    Just trying to make sure i fully understand so please correct me if I am wrong. thanks a lot for this useful snippet makes code so much more efficient without the performance hit of IIF() and evaluation quirks related to its use.

    cheers,
    tim

    • Chris says:

      You are correct, you would want to do something similar to this:

      cfqueryparam value="#arg1#" null="#not len(arg1)#"

      Thanks for the feedback.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s