To test for key existence, I recommend:
<cfif StructKeyExists(MyStruct, "mittens")>
<!--- or --->
<cfset key = "mittens">
<cfif StructKeyExists(MyStruct, key)>
Behind the scenes this calls the containsKey()
method of the java.util.map the ColdFusion struct is based on. This is arguably the fastest method of finding out if a key exists.
The alternative is:
<cfif IsDefined("MyStruct.mittens")>
<!--- or --->
<cfset key = "mittens">
<cfif IsDefined("MyStruct.#key#")>
Behind the scenes this calls Eval()
on the passed string (or so I believe) and tells you if the result is a variable reference. In comparison this is slower than StructKeyExists()
. On the plus side: You can test for a sub-key in a nested structure in one call:
<cfif IsDefined("MyStruct.with.some.deeply.nested.key")>