The Elvis operator (?:) is a small but elegant feature added in Splendor. I am going to show you how it shortens your conditional code and makes it look simpler. But before I get into the details, here is the list of language features added in ColdFusion Splendor.
- Script support for tags
- Member functions for CF data type/data structure
- Improved JSON serialization
- Easy to use CF functions for Query tag
- Elvis operator (?:)
- Promoting built-in CF function to first class
- Miscellaneous new functions: QueryGetRow, ListEach and others.
<cfscript> if(isdefined('username')){ displayName = username; } else { displayName = "anonymous"; } </cfscript>
With Elvis operator
displayName = username ?: "anonymous";
The support for Elvis operator has been provided for function calls and expressions too. Some of the expression cases are:
securityNumber = securityStruct[‘Joe’] ?: -1; // Retrieving from a struct colourCode = colourArray[index] ?: "black"; // Retrieving from an array employeeName = getEmployeeName(ID) ?: “Joe”; // A function call
@Henry, that ?: example just shows how the Adobe guys don’t actually understand how the null coalescing operator is supposed to work, and have ballsed it up.
See: http://cfmlblog.adamcameron.me/2014/02/coldfusion-11-good-stuff.html#nullCoalescingOperator
—
Adam
@James yes, but the use case is too similar.
However, I just checked out http://www.raymondcamden.com/index.cfm/2014/4/10/Recording-and-demos-from-my-ColdFusion-11-presentation and his sample demonstrates elvis operator much better.
displayName = encodeForHTML(url.name) ?: “Anonymous”;
Without the magic of the new elvis operator, it would have thrown undefined at the encodeForHTML call. It’s like adding a big hidden try/catch for the expression before the operator.
You must be logged in to post a comment.