Allow the var keyword outside of functions as alias for Variables Scope


Currently, if you copy a code snippet with the var keyword from inside a function to the body of the Component or Template, you get an error, stating that the var keyword can only be used inside a function.

Inside functions, the var keyword is an alias to the Local scope, so that the following expressions are the same:

function setX(){
  Local.x = 1;      // style-A
  var x = 1;        // style-B

But if you copy those two lines outside of the function, style-A will set x in a Struct called Local, and style-B will throw an error.

I propose that we allow the var keyword outside of a function, so that it points to the Variables scope. So that the following expressions will be the same:

component {
  variables.x = 1;
  var x = 1;        // proposal to set x in the Variables scope

There are three reasons for that:

  1. var is less typing than variables..

  2. You can copy snippets out of functions for quick testing and/or prototyping

  3. It is more consistent with both CFML and other languages like JavaScript

What do you guys think?


i like it, so that would allow var in a plain old .cfm file as well?

    var st = {};  // throws Can't invoke key ST, Local Scope can only invoked inside a Function


Yes. That way you can copy a snippet outside of a function without an error.


BTW – there’s a ticket for that. If you like it then please upvote it:


could var be allowed like this too?

    q = querynew('id');
<cfquery name="var x" dbtype="query">
	select * from q
<!-- throws invalid variable name declaration [var x] -->


Not sure about that one. I personally don’t like it, but you know that you can use

<cfquery name="Local.x" dbtype="query">

Inside a function, right? We use that construct all the time to assign a query variable to the Local scope (same as var).

Also, there has been another proposal to allow this construct (which will currently error):

var x;

So you declare the variable to set it to a specific scope, but you delay the value assignment to a later time.