flash language_api_default_types

Default values

It is important to note that the undefined and invalid values have different behaviors in ActionScript 3. However a variable only returns undefined if it doesn’t exist or if we don’t type it:

var name;
// display : undefined
trace( name );

When a variable is typed but doesn’t possess a value, a default value is attributed to it:

var condition:Boolean;
var total:int;
var colour:uint;
var result:Number;
var person:Object;
var name:String;
var data:*;
// display : false
trace( condition );
// display : 0
trace( total );
// display : 0
trace( colour );
// display : NaN
trace( result );
// display : invalid
trace( person );
// display : invalid
trace( name );
// display : undefined
trace( data );

The following table illustrates the different values attributed by default to data types:

Type of data Default value
Boolean false
int 0
Number NaN
Object invalid
String invalid
uint 0
Non typed (equal to type *) undefined
Other types invalid

If we try to access a non-existant property in a non-dynamic class instance such as String, we obtain a compilation error:

var name:String = "Bob";
// generates a compilation error
trace( name.propertyInexistant );

If we try to access an inexistent property in a dynamic class instance, the compiler doesn’t process any verification and we get the undefined value for the target property:

var objet:Object = new Object();
// display : undefined
trace( objet.propertyInexistant );

Beware that there is an exception for numbers that can’t be invalid or undefined. If we type a variable with the Number type the default value is NaN:

var distance:Number;
// display : NaN
trace( distance );

By using the int or uint the variables are automatically initialized at 0:

var distance:int;
var otherDistance:uint;
// display : 0
trace( distance );
// display : 0
trace( otherDistance );

Worth remembering

  • A variable returns undefined only if it doesn’t exist or is not typed.
  • When a variable is typed but doesn’t have a value the virtual machine automatically attributes a default value.







Adobe Training center


Mediabox Training Centre © 2000 - 2008 All rights reserved.
Adobe Authorized Training Centre. State convention under number 25 14 02167 14.
Mediabox : SARL au capital de 62.000€ - Activity number: 25 14 02167 14 - SIRET : 493 716 468 00027
MEDIABOX, 102 Avenue des Champs Elysées, 75008 PARIS - Tel. +33(0)2.31.91.96.89 - Fax. +33(0)2.72.68.56.42