Datatype Conversion

Take a closer look at the example from the previous section. In that example, each datum—“1” and 2—belonged to its own datatype; the first was a string and the second a number. We saw that the interpreter joined the two values together to form the string “12”. Note that the interpreter first had to convert the number 2 into the string “2”. Only after that automatic conversion was performed could the value “2” be joined (concatenated) to the string “1”.

Datatype conversion simply means changing the type of a datum. Not all datatype conversions are automatic; we may also change a datum’s type explicitly in order to override the default datatyping that ActionScript would otherwise perform.

Automatic Type Conversion

Whenever we use a value in a context that does not match its datatype, the interpreter attempts a conversion. That is, if the interpreter expects data of type A, and we provide data of type B, the interpreter will attempt to convert our type B data into type A data. For example, in the following code we use the string “Flash” as the righthand operand of the subtraction operator. Since only numbers may be used with the subtraction operator, the interpreter attempts to convert the string “Flash” into a number:

999 - "Flash";

Of course, the string “Flash” can’t be successfully converted into any legitimate number, so it is converted into the special numeric data value NaN (i.e., Not-a-Number). NaN is a legal value of the number datatype, intended specifically ...

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.