Recipe 1.12 Avoiding Conflicting Variables

1.12.1 Problem

You want to make sure that variables within a function do not interfere with variables in other functions or within the timeline in which the function is defined.

1.12.2 Solution

Use the var keyword to declare local variables.

1.12.3 Discussion

Generally, you should declare variables used within functions as local variables. Local variables are known only within the function. Therefore, they do not conflict with variables of the same name in other functions or within the timelines in which the functions are defined. To make a variable local, declare it with the var keyword. Parameters are automatically treated as local variables, so you do not need to include the var keyword when declaring parameters for a function.

function localVarsFunction (param1, param2) {
  var myVar;
  myVar = "Local variables are fun.";

Or, more succinctly, you can write:

function localVarsFunction (param1, param2) {
  var myVar = "Local variables are fun.";

Variables declared without the var keyword are implicitly scoped to the timeline on which they reside (note that unlike some languages, ActionScript doesn't require you to declare a variable before assigning it a value for the first time). In this case, myVar is a timeline variable, not a local variable, even though it is declared within a function:

function timelineVarsFunction (  ) {
  myVar = "Timeline variables are fun but not usually a good choice in functions.";

To declare a global variable, attach it as a property to the _global object, as follows:

_global.companyName = "Person13";

Once declared, a global variable can be accessed from anywhere in the movie by simply using its name, as follows:

trace ("Welcome to the " + companyName + "web site.");

However, a local variable of the same name will override the global variable:

function localVarsFunction (  ) {
  var companyName = "Macromedia";
  // This displays "Welcome to the Macromedia web site."
  trace ("Welcome to the " + companyName + "web site.");

  // To access the global variable of the same name, precede it with _global.
  // This displays "Welcome to the Person 13 web site."
  trace ("Welcome to the " + _global.companyName + "web site.");

For this reason, make sure that you always prefix a global variable reference with _global when you want to set its value. Otherwise, Flash will create a new local variable with the same name, which can potentially cause problems.

    Part I: Local Recipes
    Part II: Remote Recipes