coldfusion Variables Checking if a Variable Exists

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!

Example

You can check if a variable has been defined in a scope by using ColdFusion's built in StructKeyExists() function. This can be used inside a <cfif> tag to prevent error messages in the event you attempt to refer to a variable that does not exist. You can also use this function to determine whether a user has performed a certain action or not. The syntax for the function is

StructKeyExists(structure, "key")

The following example checks if the variable firstName exists in the variables scope.

<cfif StructKeyExists(variables, "firstName")>
    Hello #variables.firstname#!
<cfelse>
    Hello stranger!
</cfif>

Alternatively, you may use the function:

isDefined("scopeName.varName")

To avoid ambiguity, it is recommended to declare the scope. For example, If you have a variable in the scope test

<cfset test.name = "Tracy" />

and you test for name in the global scope, you will get a result of true.

isDefined("name") <!--- true --->
isDefined("x.name") <!--- false--->
isDefined("test.name") <!--- true --->


Got any coldfusion Question?