Application Development Tips and Tricks > Coding conventions > Using var for local variables |
![]() ![]() ![]() |
Using var for local variables
All local variables should use the keyword var
. This prevents variables from being accessed globally and, more importantly, prevents variables from being inadvertently overwritten. For example, the following code does not use the keyword var
to declare the variable and inadvertently overwrites another variable.
counter = 7; function loopTest() { trace(counter); for(counter = 0; counter < 5; counter++) { trace(counter); } } trace(counter); loopTest(); trace(counter);
This code outputs:
7 7 0 1 2 3 4 5
In this case, the counter
variable on the main Timeline is overwritten by the counter
variable within the function. Below is the corrected code, which uses the keyword counter
to declare both of the variables. Using the counter
declaration in the function fixes the bug in the code above.
var counter = 7; function loopTest() { trace(counter); for(var counter = 0; counter < 5; counter++) { trace(counter); } } trace(counter); loopTest(); trace(counter);
![]() ![]() ![]() |