Assigning data types to elements 37
Determining an item’s data type
While testing and debugging your programs, you may discover problems that seem to be related
to the data types of different items. In these cases, you may want to determine an item’s data type.
To do so, use the
typeof operator, as shown in this example:
trace(typeof(variableName));
For more information on testing and debugging, see Chapter 3, “Writing and Debugging
Scripts,” on page 55.
Assigning data types to elements
Flash automatically assigns data types to the following kinds of language elements, as discussed in
the next section, “Automatic data typing”:
• Variables
• Parameters passed to a function, method, or class
• Values returned from a function or method
• Objects created as subclasses of existing classes
However, you can also explicitly assign data types to items, which can help prevent or diagnose
certain errors in your scripts. For more information, see “Strict data typing” on page 38.
Automatic data typing
In Flash, you do not need to explicitly define an item as holding either a number, a string, or
other data type. Flash determines the data type of an item when it is assigned:
var x = 3;
In the expression var x = 3, Flash evaluates the element on the right side of the operator and
determines that it is of the number data type. A later assignment may change the type of
x; for
example, the statement
x = "hello" changes the type of x to a string. A variable that hasn’t been
assigned a value has a type of
undefined.
ActionScript converts data types automatically when an expression requires it. For example, when
you pass a value to the
trace() action, trace() automatically converts the value to a string and
sends it to the Output panel. In expressions with operators, ActionScript converts data types as
needed; for example, when used with a string, the
+ operator expects the other operand to be
astring.
"Next in line, number " + 7
ActionScript converts the number 7 to the string "7" and adds it to the end of the first string,
resulting in the following string:
"Next in line, number 7"