Not yet rated

Problem

An application wants to use the ternary operator in ColdFusion.

Solution

ColdFusion 9 allowed for the use of the ternary operator, replacing the old IIF() function.

Detailed explanation

The ternary operator is a logical operator that takes three arguments

( boolean expression )? expression1 : expression2

The boolean expression inside the parenthesis can be any exression that evaluates to a boolean. This could be a variable itself or a function that returns a boolean.  Based on the value of the boolean either expression1 is executed or expression2.  If the boolean is true expression1 is executed, otherwise, if it is false, expression2 is executed.

ColdFusion 9 added support for ternary operators, replacing the IIF() function.

Variable Example:

<cfset winOrLose = ( ManningIsQB )? "Win" : "Lose" />

In the above if ManningIsQB evaluates to true then the variable winOrLose will be set to "Win." If ManningIsQB evaluates to false, then winOrLose will be set to "Lose."

Function Example:

<cfset passingYards = ( pass.passComplete()?
.pass.getPassingYards(): 0 />

In the above example the passingYards variable is set depending on the result of the passComplete() function.  The passComplete() function of a pass object is called and returns true or false.  If the passComplete() function is true the passingYards variables is set to the result of the getPassingYards() function of the pass object.  If the passComplete() function returns false, then passingYards is set to 0.

Without the ternary operator an application might have to do something like this.

<cfif pass.passComplete()>
<cfset passingYards = pass.getPassingYards() />
<cfelse>
<cfset passingYards = 0 />
</cfif>

Using the new ternary operator in ColdFusion 9 is simple, but very powerful and cuts down on the amount of code an application needs.

 

 

 


+
This work is licensed under a Creative Commons Attribution-Noncommercial-Share Alike 3.0 Unported License. Permissions beyond the scope of this license, pertaining to the examples of code included within this work are available at Adobe.

Report abuse

Related recipes