How to check for unset style properties

Problem:

You have a component which supports a style and you want to check if the style has been set in a style sheet or on the component directly.

Solution:

When you get the value of the style, you need to store it in an untyped variable. This will allow you to check for undefined. If you store the value in an int, uint or Boolean, for example, it will be converted from undefined to the default value of that type (0, 0, or false, respectively).

Here is a simple implementation, if you don't mind losing your type.

var myStyle:* = getStyle("myStyle");
if (myStyle == undefined) {
 myStyle = 42; // appropriate default
}

Or if you're picky, you can make two variables:

var myStyleUntyped:* = getStyle("myStyle");
var myStyle:int = 42; // appropriate default
if (myStyle != undefined) {
 myStyle = myStyleUntyped;
}

Of course, there are better mechanisms for setting style defaults, and you should probably use one of those instead of hard coding the default value when you access the style (which you may have to do repeatedly).

You could also store the value in a variable typed Object. In my testing, I found that this stores null instead of undefined because an Object cannot be undefined. Only an untyped variable or an nonexistent property can be undefined.

Explanation:

Actionscript has strict rules about what values can be assigned to variables of specific types. The undefined and null values, in particular, cannot be assigned to many of the basic types. Only an untyped variable can be undefined and only variables that represent classes which are descendants of Object can be null. Numeric variables such as int and uint always have a value. The Number type can be NaN, but is never null or undefined. The String type can be null, but not undefined. The Boolean type must always be true or false and is never null or undefined.

These rules help limit the number of edge cases in the language and the impact of uninitialized variables, but can also be confusing.

Search Great Flex/Flash Sites