Test if an object is defined in ActionScript

Matthew Shanley picture Matthew Shanley · Nov 17, 2008 · Viewed 40.2k times · Source

In ActionScript, how can you test if an object is defined, that is, not null?

Answer

Matthew Crumley picture Matthew Crumley · Nov 17, 2008

test if an object is defined

This works in AS2 and AS3, and is the most reliable way to test if an object has a value.

if (obj != null) {
    doSomethingWith(obj);
}

Its also the most reliable way to test an object's property and read it in the same expression:

if (arr[0] != null && arr[0]>5) {
    doSomethingWith(arr[0]);
}

test if an object is null

There's a difference between null and undefined, but if you don't care you can just do a normal comparison between either one because they compare equal:

if (obj == null) {
    doSomethingWith(obj);
}

is the same as

if (obj == undefined) {
    doSomethingWith(obj);
}

If you care about the difference, use the === or !== operator, which won't convert them.

if (obj === undefined) {
    // obj was never assigned a value
}
else if (obj === null) {
    // obj was explicitly set to null
}
else {
    doSomethingWith(obj);
}