User Guide

About variables 29
You can assign a data type to a local variable when you define it, which helps prevent you from
assigning the wrong type of data to an existing variable. For more information, see “Strict data
typing” on page 24.
Global variables
Global variables and functions are visible to every scope in your document. To create a variable
with global scope, use the
_global identifier before the variable name and do not use the var =
syntax. For example, the following code creates the global variable
myName:
var _global.myName = "George"; // incorrect syntax for global variable
_global.myName = "George"; // correct syntax for global variable
However, if you initialize a local variable with the same name as a global variable, you dont have
access to the global variable while you are in the scope of the local variable, as shown in the
following example:
_global.counter = 100; // declares global variable
trace(counter); // accesses the global variable and displays 100
function count(){
for( var counter = 0; counter <= 2 ; counter++ ) { //local variable
trace(counter); // accesses local variable and displays 0 through 2
}
}
count();
trace(counter); // accesses global variable and displays 100
This example simply shows that the global variable is not accessed in the scope of the count()
function. To avoid confusion in your applications, name your variables uniquely.
The Flash Player version 7 and later security sandbox enforces restrictions when accessing global
variables from movies loaded from separate security domains.
Using variables in a program
You must declare and initialize a variable in a script before you can use it in an expression. If you
use an undeclared variable, as shown in the following example, the variables value will be
NaN or
undefined, and your script might produce unintended results:
var squared:Number = x*x;
trace(squared); // NaN
var x:Number = 6;
In the following example, the statement declaring and initializing the variable x comes first, so
squared can be replaced with a value:
var x:Number = 6;
var squared:Number = x*x;
trace(squared); // 36
Similar behavior occurs when you pass an undefined variable to a method or function:
//does not work
getURL(myWebSite); // no action
var myWebSite = "http://www.macromedia.com";
//works