Ask a Jedi: So what happens when you don't var scope?

So I got a good follow up question today on var scoping (Did someone decide today was Var Scope day? What do I give?) based on my earlier post. Matt asks:

I know that I am supposed to var my variables inside my cfc functions. What happens if I don't var them.

You've probably heard me preach on var scoping many times before, as well as other speakers in the ColdFusion community. So why do we keep ranting on it? The simple answer is that un-var scoped values leak. What do I mean? Consider this simple, non-cfc example. (Don't forget the 'var scoping' rule applies to both CFC methods and UDFs.)

<cfscript> function doit(x) { y = 2; return x*y; } </cfscript>


This UDF simply returns the double of a value. What makes this interesting is if you add a bit of debugging:

<cfscript> function doit(x) { y = 2; return x*y; } </cfscript>

<cfdump var="#variables#"> <cfoutput>#doit(10)#</cfoutput> <cfdump var="#variables#">

When you first run it, the Variables scope only contains the UDF. But when you run it again, y is now defined as 2. So why is this a big deal? Consider this example:

<cfscript> function doit(x) { y = 2; return x*y; } </cfscript>

<cfset y = 199> <cfset doubley = doit(y)> <cfoutput> Our original value is #y#, and double it is #doubley# </cfoutput>

I've taken a variable, Y, and stored a value in it. I then call my UDF to get the double of it - then I output the results. If you run this, you will see:

Our original value is 2, and double it is 398

This is certainly not what we want and it clearly shows the negative side effects of missing var statements. In my example it was relatively easy to track down since the UDF was on page, but in a CFC it could be much harder to figure out. Missing var scopes are one of the most difficult bugs to track down.

Raymond Camden's Picture

About Raymond Camden

Raymond is a developer advocate for HERE Technologies. He focuses on JavaScript, serverless and enterprise cat demos. If you like this article, please consider visiting my Amazon Wishlist or donating via PayPal to show your support. You can even buy me a coffee!

Lafayette, LA