4.8 Undefined

ActionScript for Flash MX: The Definitive Guide, 2nd Edition
By Colin Moock
Chapter 4.  Primitive Datatypes

Most of the datatypes we've explored so far have been used for storing and manipulating information. The undefined datatype has a more narrow purpose: it is used to check whether a variable exists or whether a variable has been assigned a value yet. The undefined datatype has only one legal value, the primitive value undefined.

When we first define a variable, it is assigned the value undefined by default:

var velocity;

To the interpreter, the preceding statement reads:

var velocity = undefined;

To check whether a variable has a value, we can compare the variable to undefined, as in:

if (myVariable !=  = undefined) {   // myVariable has a value, so proceed as desired... }

To remove a variable or object property, you should use the delete operator rather than assigning the value undefined to the variable or property. Assigning undefined to a property leaves the property intact but merely sets its value to undefined. Deleting the property removes it entirely.

Note that, in ActionScript, an undefined value is converted to the empty string when used as a string. For example, in the following code we create two variables, firstName and lastName, which we concatenate together and assign to the variable fullName. The variable firstName has no value (the value is undefined), so it converts to "".

var firstName; var lastName = "Moock"; var fullName = firstName + lastName;  // Sets fullName to "Moock"

In JavaScript, the undefined value is converted to the string "undefined" when used in a string context, so the above code in JavaScript would assign the value "undefinedMoock" to fullName. ActionScript converts undefined to "" for the sake of backward compatibility. However, in Flash MX and later, when an undefined value is sent to the Output window via the trace( ) function, the word "undefined" appears (this makes undefined easier to detect during debugging).

Because there was no undefined type in Flash 4 ActionScript, many Flash 4 programs used the empty string to check whether a variable had a useful value. Code like this was common in Flash 4:

if (myVar eq "") {    // Don't do anything yet: myVar is undefined  }

If Flash converted undefined to anything other than "" in a string context, old code such as this wouldn't work in Flash Player 5 and later.

Note that ActionScript returns undefined for both variables that do not exist and variables that have been declared but have no value. This is also a departure from JavaScript, where references to variables that do not exist cause an error.

     



    ActionScript for Flash MX. The Definitive Guide
    ActionScript for Flash MX: The Definitive Guide, Second Edition
    ISBN: 059600396X
    EAN: 2147483647
    Year: 2002
    Pages: 780
    Authors: Colin Moock

    flylib.com © 2008-2017.
    If you may any questions please contact us: flylib@qtcs.net