Saturday 4 August 2012

ColdFusion Local Scope

The following code demonstrates the problem...
Output: GONE

As you can see, function2 overwrites the data variable that we are trying to use in function1. By adding the var keyword to our variable declarations we ensure that the variable is local to that function and cannot be accessed outside of it, meaning that even if the same variable name is used outside of the function it wont be overwritten.
Output: Hello world

The problem may seem pretty obvious here in this example but in a much bigger application it could cause a lot of problems. Perhaps someone else wrote function2, it may do something completely unrelated to your data variable and it almost certainly wouldn't be coded right bellow function1 like it is in this example.

Running into a problem like this could take a while to figure out if you're not looking out for it so remember, ALWAYS var scope your function variables!