Archive for January, 2003

Using the “var” Keyword to Scope Variables in ColdFusion Components

I’ve seen a fair number of posts recently regarding the use of the “var” keyword inside of ColdFusion components. I posted a pretty comprehensive explanation on cfcdev, but both for posterity and for those who might have missed it, I will re-post it here (along with some additional information).

All local variables used within a cffunction should be declared at the top of your function (under your cfargument tags), including query names. For instance:

<cffunction...>
<cfargument ... />
<cfset var queryName = "" />
<cfquery name="queryName">
some query...
</cfquery>
</cffunction>

It is a matter of scoping. Using “var” makes variables local to the function rather than being global in scope where they can stomp on other variables. It’s the same in JavaScript:

function returnFoo()
{
var myVar = "foo";
return myVar;
}

In the function above, if you were to remove the var keyword, myVar would be a global variable, which you rarely want. Though it usually does not cause a problem in either JavaScript or ColdFusion, when it does, it can be extremely difficult to find the bug. You are much better off coding your CFCs, UDFs and JavaScript functions as tightly as you can.

The big difference between JavaScript and CFC functions regarding the use of var is that in ColdFusion, all variables declared using the var keyword have to be declared at the top of the function, whereas in JavaScript, you can declare them anywhere inside of a function.

User defined functions are similar to CFCs in that declarations must be made at the top of the function. They cannot be made anywhere else and they must be contained within a function (as opposed to just cfscript tags).

Christian Cantrell’s Perspective – From the Macromedia Server Community Manager

Welcome to Christian Cantrell’s Perspective, the weblog of the Macromedia Server Community Manager. This is where you will find news and information about Macromedia-related topics with an emphasis on ColdFusion and JRun (along with the occasional off-topic post). You can contribute to posts by clicking on the “Comments” tab, access other resources by clicking on the “Resources” tab or pull down my RSS news feed at the following URL:

http://markme.com/cantrell/weblog/rss.xml

I guess you could say my blog is currently in beta. I wrote it in just a few days and I’m constantly making tweaks, so don’t be surprised if you stumble across a bug. If you find something of interest, please send me an email (cantrell@macromedia.com) and I’ll get it fixed up. I also take feature requests.

Drop me a line if there is anything in particular you would like me to write about. Otherwise I will just wait and see what catches my attention.

Christian Cantrell