Learning to Like the Var Keyword

Coming from four years of Java programming, I was a little annoyed at first back in the Neo days when I discovered that local variable declarations using the keyword “var” had to come at the top of your functions. It seemed primitive and inconvenient. I have since come to appreciate it, however, and now I actually like it. Once your component functions get long and involved enough, it is sometimes easy to forget whether a particular variable name has already been used in a function. In most cases, it wouldn’t matter if you were to inadvertently reuse a variable name, however in some cases, it could certainly cause unexpected and unintended behavior (aka bugs). When encountering the same situation in Java, I used to do a quick search within the scope of a function before declaring a new variable (although with Java, the compiler will catch errors like that for you). In ColdFusion MX, I now go the top of the function and add the variable declaration in alphabetical order, and if the variable name is already in use, I will notice right away. After quite a bit of component development, I now find that variable declaration at the top of my functions is completely natural and actually helpful.

2 Responses to Learning to Like the Var Keyword

  1. One thing I remind people of is to not forget to var scope each and every single local variable, including these easy to forget items:Loop counters (x,y,i, etc)Queries. Don’t forget that when you do cfquery name=”foo”, you are creating a variable called foo.

  2. Thanks Raymond. I had no idea.