Code Tip: Declaring Variables Locally

December 22nd, 2008 by Jim Burrows

When declaring a variable, it's good practice to declare it as locally as possible. For instance, if you have a function that uses a variable, it's best to declare the variable within that function.

bad code:

var count:int;
function badCode():void{
     for(var i:int=0; i<100; i++){
          count=i;
     }
}

good code:

function goodCode():void{
     for(var i:int=0; i<100; i++){
          var count=i;
     }
}

In the second example, the variable "count" is declared and initialized locally within the function. Because of this, "count" will get garbage collected when the function is done running.

Leave a Reply

RSS Feed