Determining if a variable has been defined in ColdFusion

Readability

Determining if a variable has been defined in ColdFusion

The fol­low­ing exam­ple shows how you can check if a vari­able has been defined in Cold­Fu­sion by using the isDefined() method.


    Yes, you can has.

    Want cheeseburger?

If Cold­Fu­sion can­not find an iCan­HasCheese­burger vari­able in the #URL# scope (or the #URL.iCanHasCheeseburger# vari­able is false/​no, the <cfif> block eval­u­ates to false and the <cfelse> block is executed.

The following example shows how you can check if a variable has been defined in ColdFusion by using the isDefined() method.

<cfif isDefined("URL.iCanHasCheeseburger") && URL.iCanHasCheeseburger>
    <strong>Yes, you can has.</strong>
<cfelse>
    <cfoutput><a href="#CGI.SCRIPT_NAME#?iCanHasCheeseburger=yes">Want cheeseburger?</a></cfoutput>
</cfif>

If ColdFusion cannot find an iCanHasCheeseburger variable in the #URL# scope (or the #URL.iCanHasCheeseburger# variable is false/no, the <cfif> block evaluates to false and the <cfelse> block is executed.

2 thoughts on “Determining if a variable has been defined in ColdFusion”

  1. I think it’s a really bad idea to show the example without also pointing out that using StructKeyExists() performs better than isDefined().

    The example can also, and should, be written as …

Leave a Reply

Your email address will not be published.