Changing and Retrieving Variable Values

After we’ve created a variable, we may assign and reassign its value as often as we like, as shown in Example 2.1.

Example 2-1. Changing Variable Values

var firstName;                   // Declare the variable firstName
firstName = "Graham";            // Set the value of firstName
firstName = "Gillian";           // Change the value of firstName
firstName = "Jessica";           // Change firstName
                   again
firstName = "James";             // Change firstName
                   again
var x = 10;                      // Declare x and assign a numeric value
x = "loading...please wait...";  // Assign x a text value

Notice that we changed the variable x’s datatype from numeric to text data by simply assigning it a value of the desired type. Some programming languages don’t allow the datatype of a variable to change but ActionScript does.

Of course, creating variables and assigning values to them is useless if you can’t retrieve the values later. To retrieve a variable’s value, simply use the variable’s name wherever you want its value to be used. Anytime a variable’s name appears (except in a declaration or on the left side of an assignment statement), the name is converted to the variable’s value. Here are some examples:

newX = oldX + 5;  // Set newX to the value of oldX plus 5
ball._x = newX;   // Set the horizontal position of the
                  // ball movie clip to the value of newX
trace(firstName); // Display the value of firstName in the Output window

Note that in the expression ball._x, ball is a movie clip’s name, and the ._x indicates its x-coordinate property ...

Get ActionScript: The Definitive Guide now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.