CF9: One Difference Between the New Ternary Operator and IIF()
When I first saw the ternary operator in java, I confess I did not like it. To my way of thinking, it was odd and cryptic, and I did not see the advantage over a standard if/else statement. Well, I have come a long way. For simple comparisons I now prefer its sleeker syntax over the more bulky if/else construct.
So it was quite pleasing to see the ternary introduced in ColdFusion 9. I never much cared for the IIF() function. (Too reminiscent of MS Access I suppose) But stylistic preferences aside, I just noticed the behavior of the ternary operator differs from IIF() in another sense. It uses delayed evaluation.
Take this silly example. When someCondition is true, only the variable foo is defined. <cfset someCondition = true />
<cfif someCondition>
<cfset foo = 123>
<cfelse>
<cfset foo = 321>
<cfset bar = 88>
</cfif>
If you are using the new ternary operator, a statement like the one below would succeed. It does not matter that the variable bar is not defined. Because the second variable is only evaluated when someCondition is false.
<cfset result = someCondition ? foo : bar />
However, using IIF(), both variables are evaluated immediately, whether they are used or not. So this code would result in an error: "variable BAR is undefined"
To avoid the error you would need to use the DE() function, which just feels awkward to me.
<cfset result = IIF(someCondition, foo, bar) />
<cfset result = IIF(someCondition, foo, DE("bar")) />
So in this sense at least, the ternary operator is a bit smarter than the old IIF() function.
