Variables allow you to store values that you use in your program. To declare a variable, you must use the var statement with the variable name. In ActionScript 2.0, use of the var statement is only required if you use type annotations. In ActionScript 3.0, use of the var statement is always required. For example, the following line of ActionScript declares a variable named i:
var i;
To associate a variable with a data type, you must do so when you declare the variable. Declaring a variable without designating the variable’s type is legal, but will generate a compiler warning in strict mode. You designate a variable’s type by appending the variable name with a colon (“:”), followed by the variable’s type. For example, the following code declares a variable i that is of type int:
var i:int;
You can assign a value to a variable using the assignment operator (“=”). For example, the following code declares a variable i and assigns the value of 20 to it:
var i:int;
i = 20;
You may find it more convenient to assign a value to a variable at the same time that you declare the variable:
var i:int = 20;
The technique of assigning a value to a variable at the time it is declared is commonly used not only when assigning primitive values such as int and String, but also when creating an array or instantiating an instance of a class. The following example shows an array declared and assigned a value using one line of code.
var numArray:Array = ["zero", "one", "two"];
You can create an instance of a class by using the new operator. The following example creates an instance of a named CustomClass, and assigns a reference to the newly created class instance to the variable named customItem.
var customItem:CustomClass = new CustomClass();
If you have more than one variable to declare, you can declare them all on one line of code by using the comma operator (“,”) to separate the variables. For example, the following code declares three variables on one line of code.
var a:int, b:int, c:int;
You can also assign values to each of the variables on the same line of code. For example, the following code declares three variables (a, b and c) and assigns each a value.
var a:int = 10, b:int = 20, c:int = 30;
Although you can use the comma operator to group variable declarations into one statement, doing so may reduce the readability of your code.