:::: MENU ::::

Mastering property existence with the hasOwnProperty method

For a long time I’ve struggled with determining whether or not a property exists in Actionscript 3.0. Like many people, I would often find myself writing somewhat tediously repetitive conditional checks such as:

Other than the fact that this is a lot of code to write (especially when you have a long conditional that checks 10 or 15 properties), this would work “most” of the time. I say most, because if the property you were trying to validate didn’t exist at all (i.e. there is no property name “myProperty” in your object), then you would get a nice “null object reference” error.

Enter hasOwnProperty(). Now, as usual, I’m sure I’m more than a little late in discovering this handy little method, but if it took me this long to find it, then I’m sure there’s more than a few other lost soles out there that are in the same boat, so this one’s for you guys! As defined in the Adobe LiveDocs, the hasOwnProperty method “Indicates whether an object has a specified property defined.” Sounds simple enough, and it really is. Where this becomes useful is when you want to first check for the existence of a property prior to checking its’ value (and thus avoiding the evil null object reference).

Below is a simple ObjectUtils class that I wrote that currently has a single method called “propertyExists”. The propertyExists method simply implements the hasOwnProperty method, then goes a step further to check for a valid (not null or undefined) value.

To implement this method and check for a valid property, you would do something like this:



So, what do you think ?