Book HomeActionScript: The Definitive GuideSearch this book

2.3. 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 (i.e., horizontal position on stage). We'll learn more about properties later. The last line, trace(firstName), displays a variable's value while a script is running, which is handy for debugging your code.

2.3.1. Checking Whether a Variable Has a Value

Occasionally we may wish to verify that a variable has been assigned a value before we make reference to it. As we learned earlier, a variable that has been declared but never assigned a value contains the special "non-value," undefined. To determine whether a variable has been assigned a value, we compare that variable's value to the undefined keyword. For example:

if (someVariable != undefined) {
  // Any code placed here is executed only if someVariable has a value
}

Note the use of the inequality operator, !=, which determines whether two values are not equal.



Library Navigation Links

Copyright © 2002 O'Reilly & Associates. All rights reserved.