Requirements

Prerequisite knowledge

You should be familiar with ActionScript 3 syntax and variables.

User level

Beginning

Data typing is the ability to give both the compiler and Flash Player information about the type of data stored in memory. By providing this information, the tools and can check to ensure your code doesn't perform illogical operations, such as trying to assign the word "help" to a date object. Further, based upon this type information, Flash Player can make more intelligent decisions leading to faster execution of your program.

In this article, you will learn what a data type is and how to specify the type of data your variables will contain. You will learn the basic types of data used by Flash Player and how to convert between them.

Data types

Computers handle different types of data differently. Possible values, operations that can be performed, and storage methods vary across the types of data a programming language supports. Assigning the data type for a variable limits what the variable can contain, what can be done to the value, and how it is stored.

Using data types can seem like an extra step because you must plan how your application handles data before you start writing code. However, when you use data types, your code is more predictable and your applications are more stable. Data types are also invaluable during the debugging process.

Think about the toy that helps toddlers learn to recognize shapes. Star shaped blocks only fit in the star holes. Cubes only fit in the square holes. Cylinders only fit in the circle holes. The box gives toddlers an immediate error—the block doesn't fit—when they try to put the star into the square hole. Similarly, the computer throws an error when you try to fit one type of data into a variable that was typed with a different data type.

ActionScript 3 has many data types to use as the type for the variables you create. A primitive value is a value that belongs to one of the following data types: String , Number , int , uint , Boolean , Null , and void .

  • String : a textual value, like a name or the text of a book chapter
  • Numeric: ActionScript 3 includes three specific data types for numeric data:
    • Number : any numeric value, including values with or without a fraction
    • int : an integer (a whole number without a fraction)
    • uint : an "unsigned" integer, meaning a whole number that is not negative
  • Boolean : a true-or-false value, such as whether a switch is on or whether two values are equal

Primitive values are usually faster than complex values because ActionScript 3 stores primitive values in a special way that makes memory and speed optimizations possible.

Note: For readers interested in the technical details, ActionScript 3 stores primitive values internally as immutable objects. The fact that they are stored as immutable objects means that passing by reference is effectively the same as passing by value. This cuts down on memory usage and increases execution speed, because references are usually significantly smaller than the values themselves.

A complex value is a value that is not a primitive value. Data types that define sets of complex values include: Object, Array, Date, Error, Function, RegExp, XML, and XMLList. All values in ActionScript 3, whether they are primitive or complex, are objects.

The ActionScript 3 core classes include all of the primitive and complex data types listed above. The core classes allow you to create objects using literal values instead of using the new operator. For example, you can create an array using a literal value or the Array class constructor, as follows:

var someArray:Array = [1, 2, 3]; // literal value var someArray:Array = new Array(1,2,3); // Array constructor

Type checking

Type checking can occur at either compile time or runtime. Statically typed languages report type errors at compile time, which requires type information to be known at compile time. Dynamically typed languages type check at runtime which allows flexibility in code structure. However, in runtime reporting, type errors are not discovered until later. As a dynamically typed language, ActionScript 3 has runtime type checking. However, in strict mode, type checking occurs at both compile time and runtime. In standard mode, type checking occurs only at runtime.

Compile-time type checking

Compile-time type checking is favored as a project's size grows because catching type errors as early as possible becomes more important than data type flexibility. By default, the ActionScript compiler in Flash Professional and Flash Builder is set to run in strict mode to catch errors early.

To provide compile-time type checking, the compiler must know the data type information for the variables or expressions in your code. To explicitly declare a data type for a variable, use the colon operator (:) followed by the data type as a suffix to the variable name. To associate a data type with a parameter, use the colon operator followed by the data type. For example, the following code adds data type information to the sampleParameter parameter and declares a variable sampleData with an explicit data type:

function runtimeTest(sampleParameter:String){ trace(sampleParameter); } var sampleData:String = “hello”; runtimeTest(sampleData);

In strict mode, the ActionScript compiler reports type mismatches as compiler errors. For example, the following code declares a function parameter sampleParameter , of type Object, but later attempts to assign values of type String and Number to that parameter. In strict mode, a compiler error results.

function dynamicTest(sampleParameter:Object){ if (sampleParameter is String){ var exampleString:String = sampleParameter; // compiler error in strict mode trace("String: " + exampleString); } else if (sampleParameter is Number){ var exampleNumber:Number = sampleParameter; // compiler error in strict mode trace("Number: " + exampleNumber); } }

Runtime type checking

Runtime type checking occurs in ActionScript 3 whether you compile in strict mode or standard mode. Consider a situation in which the value 3 is passed as an argument to a function that expects an array. In strict mode, the compiler generates an error, because the value 3 is not compatible with the data type Array. If you run in standard mode, the compiler does not complain about the type mismatch, but runtime type checking results in a runtime error.

The following example shows a function named typeTest() that expects an Array argument but is passed a value of 3. The incorrect type causes a runtime error in standard mode, because the value 3 is not a member of the parameter's declared data type (Array).

function typeTest(sampleParameter:Array){ trace(sampleParameter); } var exampleNumber:Number = 3; typeTest(exampleNumber); // runtime error in ActionScript 3 standard mode

There are also situations where you get a runtime type error even when you are operating in strict mode. This error is possible if you use strict mode, but opt out of compile-time type checking by using an untyped variable. When you use an untyped variable, you are not eliminating type checking but rather deferring it until runtime. For example, if the exampleNumber variable in the previous example does not have a declared data type, the compiler cannot detect the type mismatch. However, a runtime error occurs because ActionScript compares the runtime value of exampleNumber, which is 3, with the type of sampleParameter, which is set to the Array data type.

function typeTest(sampleParameter:Array){ trace(sampleParameter); } var exampleNumber = 3; typeTest(exampleNumber); // runtime error in ActionScript 3

Data type descriptions

The primitive data types include Boolean , int , Null , Number , String , uint , and void . The ActionScript core classes also define the following complex data types: Object , Array , Date , Error , Function , RegExp , XML , and XMLList .

Boolean data type

The Boolean data type includes two values: true and false . No other values are valid for variables of Boolean type. The default value of a Boolean variable that has been declared but not initialized is false .

Number data type

In ActionScript 3, the Number data type can represent all types of numbers—integers, unsigned integers, and floating-point numbers. It is the most flexible of numeric data types in ActionScript 3. However, to maximize performance, use the Number data type only for floating-point numbers or for integer values larger than the 32-bit int and uint types can store.

Storage of floating-point numbers

The Number data type uses the 64-bit double-precision format as specified by the IEEE Standard for Binary Floating-Point Arithmetic (IEEE-754). This standard dictates how floating-point numbers are stored using the 64 available bits. One bit is used to designate whether the number is positive or negative. Eleven bits are used for the exponent, which is stored as base 2. The remaining 52 bits are used to store the significand (also called mantissa), the number that is raised to the power indicated by the exponent.

By using some of its bits to store an exponent, the Number data type can store floating-point numbers significantly larger than if it used all of its bits for the significand. For example, if the Number data type used all 64 bits to store the significand, it could store a number as large as 265 – 1. By using 11 bits to store an exponent, the Number data type can raise its significand to a power of 21023.

Although this range of numbers is enormous, it comes at the cost of precision. Because the Number data type uses 52 bits to store the significand, numbers that require more than 52 bits for accurate representation, such as the fraction 1/3, are only approximations. If your application requires absolute precision with decimal numbers, use software that implements decimal floating-point arithmetic as opposed to binary floating-point arithmetic.

To store a floating-point number, include a decimal point in the number. If you omit a decimal point, the number is stored as an integer.

NaN and other special Number values

The default value of an unassigned Number variable is NaN . The NaN value is also the result of any operation that should return a number but does not. For example, if you attempt to calculate the square root of a negative number or divide 0 by 0, the result is NaN . Other special Number values include positive infinity and negative infinity.

Note: The result of division by 0 is only NaN if the divisor is also 0. Division by 0 produces infinity when the dividend is positive or –infinity when the dividend is negative.

int data type

The int data type includes all positive and negative whole numbers from –2,147,483,648 (–231) through 2,147,483,647 (231 – 1) inclusive. It is stored as a 32-bit integer. If you do not need floating-point numbers, use the int type instead of Number because it is faster and more efficient. For values outside the range of int , use the Number data type. The int type is commonly used in counters and loops. The default value for unassigned int variables is 0.

If you try to assign a floating-point value to an int variable, ActionScript ignores the fractional (decimal) part.

uint data type

The uint data type includes all positive whole numbers from 0 through 4,294,967,295 (232 – 1) inclusive. It is stored as a 32—bit integer. The default value for unassigned uint variables is 0. As with int , if you try to assign a floating-point value to a uint variable, ActionScript ignores the fractional (decimal) part.

A uint value is always a simple binary translation of the value. Use a uint for all bit math and when working with hexadecimal values for color.

Null data type

The Null data type contains only one value, null . This value is the default value for the String data type and all classes that define complex data types, including the Object class. None of the other primitive data types, Boolean , Number , int , and uint , contain the value null . At runtime, the value null is converted to the appropriate default value if you attempt to assign null to variables of type Boolean , Number , int , or uint .

Do not confuse value null with the special value undefined . When null and undefined are compared with the equality ( == ) operator, they compare as equal. However, when null and undefined are compared with the strict equality ( === ) operator, they compare as not equal.

String data type

The String data type represents a sequence of 16-bit characters. Strings are stored internally as Unicode characters, using the UTF-16 format. Strings are immutable values. An operation on a String value returns a new instance of the string. The default value for a variable declared with the String data type is null . The value null is not the same as the empty string ( "" ). The value null means that the variable has no value stored in it. The empty string means that the variable has a value that is a String containing no characters.

void data type

The void data type contains only one value, undefined . You can only assign a value of undefined to variables that are untyped. Untyped variables are variables that either lack any type annotation, or use the asterisk ( * ) symbol for type annotation. You can use void only as a return type annotation.

Object data type

The Object class defines the Object data type. The Object class serves as the base class for all class definitions in ActionScript. The default value for instances of the Object class is null .

Default values

A default value is the value that a variable contains before you set its value. You initialize a variable when you assign it a value for the first time. If you declare a variable, but do not assign it a value, that variable is uninitialized. The value of an uninitialized variable depends on its data type. The following table describes the default values of variables, organized by data type:

Table 1. Default values for primitive data types

Data type

Default value

Boolean

false

int

0

Number

NaN

Object

null

String

null

uint

0

Not declared (equivalent to type annotation *)

undefined

All other classes, including user-defined classes.

null

If you declare a variable, but do not declare its data type, the default data type * applies, which actually means that the variable is untyped. If you also do not initialize an untyped variable with a value, its default value is undefined .

The value null is not a valid value for variables of type Boolean , Number , int , or uint . If you attempt to assign a value of null to a such a variable, the value is converted to the default value for that data type. For variables of type Object , you can assign a value of null . If you attempt to assign the value undefined to a variable of type Object , the value is converted to null .

Type conversions

A type conversion is said to occur when a value of one data type is transformed into a value of a different data type. Type conversions can be either implicit or explicit. Implicit conversion, also called coercion, is sometimes performed at runtime. For example, if the value 2 is assigned to a Boolean typed variable, the value 2 is converted to the Boolean value true before assignment. Explicit conversion, also called casting, occurs when your code instructs the compiler to treat a variable of one data type as if it belongs to a different data type. When primitive values are involved, casting actually converts values from one data type to another. To cast an object to a different type, you wrap the object name in parentheses and precede it with the name of the new type. For example, the following code takes a Boolean value and casts it to an integer:

var myBoolean:Boolean = true; var myINT:int = int(myBoolean); trace(myINT); // 1

Implicit conversions

Implicit conversions happen at runtime in a number of contexts:

  • In assignment statements
  • When values are passed as function arguments
  • When values are returned from functions
  • In expressions using certain operators, such as the addition (+) operator

For user-defined types, implicit conversions succeed when the value to be converted is an instance of the destination class or a class that derives from the destination class. If an implicit conversion is unsuccessful, an error occurs. For example, the following code contains a successful implicit conversion and an unsuccessful implicit conversion:

class A {} class B extends A {} var objectA:A = new A(); var objectB:B = new B(); var sampleArray:Array = new Array(); objectA = objectB; // Conversion succeeds. objectB = sampleArray; // Conversion fails.

For primitive types, implicit conversions are handled by calling the same internal conversion algorithms that are called by the explicit conversion functions.

Explicit conversions

It's helpful to use explicit conversions when you compile in strict mode, because there are times when you do not want to generate a compile-time error. Use explicit conversions when you know that coercion will convert your values correctly at runtime. For example, when working with data received from a form, cast certain string values to numeric values. The following code generates a compile-time error even though the code would run correctly in standard mode:

var quantityField:String = "3"; var quantity:int = quantityField; // compile time error in strict mode

If you want to continue using strict mode, but would like the string converted to an integer, you can use explicit conversion, as follows:

var quantityField:String = "3"; var quantity:int = int(quantityField); // Explicit conversion succeeds.

Casting to int , uint , and Number

You can cast any data type into one of the three number types: int , uint , and Number. If the number can't be converted, the default value of 0 is assigned for int and uint data types, and the default value of NaN is assigned for the Number data type. If you convert a Boolean value to a number, true becomes the value 1 and false becomes the value 0.

var exampleBoolean:Boolean = true; var exampleUINT:uint = uint(exampleBoolean); var exampleINT:int = int(exampleBoolean); var exampleNumber:Number = Number(exampleBoolean); trace(exampleUINT, exampleINT, exampleNumber); // 1 1 1 exampleBoolean = false; exampleUINT = uint(exampleBoolean); exampleINT = int(exampleBoolean); exampleNumber = Number(exampleBoolean); trace(exampleUINT, exampleINT, exampleNumber); // 0 0 0

String values that contain only digits can be successfully converted into one of the number types. The number types can also convert strings that look like negative numbers or strings that represent a hexadecimal value (for example, 0x1A ). The conversion process ignores leading and trailing white space characters in the string value. You can also cast strings that look like floating-point numbers using Number() . The inclusion of a decimal point causes uint() and int() to return an integer, truncating the decimal and the characters following it. For example, the following string values can be cast into numbers:

trace(uint("5")); // 5 trace(uint("–5")); // 4294967291. It wraps around from MAX_VALUE trace(uint(" 27 ")); // 27 trace(uint("3.7")); // 3 trace(int("3.7")); // 3 trace(int("0x1A")); // 26 trace(Number("3.7")); // 3.7

String values that contain non-numeric characters return 0 when cast with int() or uint() and NaN when cast with Number() . The conversion process ignores leading and trailing white space, but returns 0 or NaN if a string has white space separating two numbers.

trace(uint("5a")); // 0 trace(uint("ten")); // 0 trace(uint("17 63")); // 0

Casting is not necessary when a value of one numeric type is assigned to a variable of a different numeric type. Even in strict mode, the numeric types are implicitly converted to the other numeric types. In some cases, this implicit conversion causes unexpected values to result when the range of a type is exceeded. The following examples all compile in strict mode, though some generate unexpected values:

var exampleUint:uint = –3; // Assign int/Number value to uint variable trace(exampleUint); // 4294967293 var exampleNumber:Number = exampleUint; // Assign int/uint value to Number variable trace(exampleNumber) // 4294967293 var exampleInt:int = Number.MAX_VALUE + 1; // Assign Number value to int variable trace(exampleInt); // 0 exampleInt = uint.MAX_VALUE + 1; // Assign uint value to int variable trace(exampleInt); // 0

The following table summarizes the results of casting to the Number, int, or uint data type from other data types.

Table 2. Results of casting to numerical data type

Data type or value

Result of conversion to Number, int , or uint

Boolean

If the value is true , 1; otherwise, 0.

Date

The internal representation of the Date object, which is the number of milliseconds since midnight January 1, 1970, universal time.

null

0

Object

If the instance is null and converted to Number , NaN ; otherwise, 0.

String

A number if the string can be converted to a number; otherwise, NaN if converted to Number , or 0 if converted to int or uint .

undefined

If converted to Number , NaN ; if converted to int or uint , 0.

Casting to Boolean

Casting to Boolean from any of the numeric data types ( uint , int , and Number ) results in false if the numeric value is 0, and true otherwise. For the Number data type, the value NaN also results in false . The following example shows the results of casting the numbers –1, 0, and 1:

var numberToCast:Number; for (numberToCast = –1; numberToCast<2; numberToCast++){ trace("Boolean(" + numberToCast +") is " + Boolean(numberToCast)); }

The output from the example shows that, of the three numbers, only 0 returns a value of false :

Boolean(–1) is true Boolean(0) is false Boolean(1) is true

Casting to Boolean from a String value returns false if the string is either null or an empty string (""). Otherwise, it returns true .

var stringToCast:String; // Uninitialized string is null. trace(Boolean(stringToCast)); // false var emptyStringToCast:String = ""; // empty string trace(Boolean(emptyStringToCast)); // false var wsStringToCast:String = " "; // white space only trace(Boolean(wsStringToCast)); // true

Casting to Boolean from an instance of the Object class returns false if the instance is null ; otherwise, it returns true :

var objectToCast:Object; // Uninitialized object is null. trace(Boolean(objectToCast)); // false objectToCast = new Object(); // instantiate trace(Boolean(objectToCast)); // true

Boolean variables get special treatment in strict mode in that you can assign values of any data type to a Boolean variable without casting. In other words, unlike almost all other data types, casting to Boolean is not necessary to avoid strict mode errors. The following examples all compile in strict mode and behave as expected at runtime:

var objectToCast:Object = new Object(); var sampleBoolean:Boolean = objectToCast; trace(sampleBoolean); // true sampleBoolean = "random string"; trace(sampleBoolean); // true sampleBoolean = new Array(); trace(sampleBoolean); // true sampleBoolean = NaN; trace(sampleBoolean); // false

The following table summarizes the results of casting to the Boolean data type from other data types:

Table 3. Results of casting to Boolean

Data type or value

Result of conversion to Boolean

String

false if the value is null or the empty string (""); true otherwise

null

false

Number, int, or uint

false if the value is NaN or 0; true otherwise.

Object

false if the instance is null ; true otherwise.

Casting to String

Casting to the String data type from any of the numeric data types returns a string representation of the number. Casting to the String data type from a Boolean value returns the string " true " if the value is true , and returns the string " false " if the value is false .

Casting to the String data type from an instance of the Object class returns the string " null " if the instance is null . Otherwise, casting to the String type from the Object class returns the string "[object Object]" .

Casting to String from an instance of the Array class returns a string made up of a comma-delimited list of all the array elements. For example, the following cast to the String data type returns one string containing all three elements of the array:

var sampleArray:Array = ["primary", "secondary", "tertiary"]; trace(String(sampleArray)); // primary,secondary,tertiary

Casting to String from an instance of the Date class returns a string representation of the date that the instance contains. For example, the following example returns a string representation of the Date class instance (the output shows result for Pacific Daylight Time):

var sampleDate:Date = new Date(2005,6,1); trace(String(sampleDate)); // Fri Jul 1 00:00:00 GMT-0700 2005

The following table summarizes the results of casting to the String data type from other data types.

Table 4. Results of casting to String

Data type or value

Result of conversion to string

Array

A string made up of all array elements.

Boolean

" true " or " false "

Date

A string representation of the Date object.

null

" null "

Number, int, or uint

A string representation of the number.

Object

If the instance is null, " null "; otherwise, "[object Object]".

Where to go from here

Data typing is a fundamental concept to ActionScript 3. It allows the compiler to watch for simple and easily correctable mistakes during development and allows the Flash Player to execute code more quickly at runtime.

These data types will be used throughout development and are often used as parameters to functions and properties of objects. To learn more about each of these read ActionScript 3 fundamentals: Functions and Introduction to objects (coming October 31).

Acknowledgement

The content in this article is based on material originally published in the Learning ActionScript 3 user guide created by Adobe Community Help and Learning.