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:

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

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).

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

  1. Mike Tangorre says:

    I have a function called setFullAddress and I use:cfset var fullAddress = structNew()cfset fullAddress.part1 = getAddress1()cfset fullAddress.part2 = getAddress2()cfset = getCity()cfset fullAddress.state = getState()cfset fullAddress.zipcode = getZipcode()Then I have a function witha return type of struct that returns fullAddressMy question is… how do you use “var” with structures? Do you only var the first line like I have or do you need to var each key in the structure?My getFullAddress function does not work right…

  2. amigos says:

    Where can I found more information about this?TIA

  3. Yasmin says:

    Yes, the use of “var” in javascript is not strict. You can use it anywhere. That is one thing about javascript, it has very “loose” rules concerning syntax and so forth.

  4. Wellbutrin says:

    Yes, when you have a structure like that you would just use var when defining the structure, and not with each key value. I believe you will get an error you try to var each key value.

  5. Well now, if you use “var” within a function in javascript, it localizes that variable to only that function. Very good to know !