Sep 25 2008
Testing for null Objects
I am not sure how many Flex/Flash programmers are aware of this fact or also you might call me to be a noob on this point but i discovered this today in AS 3.0, I just use ! to find if the object is null or not and don’t bother testing against another property within that object but sometimes there is no other way around it.
Consider the following example,
//this is standard way of finding if the objects are null or not
//since the object is initialized there should not be a trace
if (!strObj){
trace("this shouldn't be happening");
}
But the trace statement shows up, it almost seems that Flash is treating this object as null but no if you look at the variable using the debugger the value is not null. So this isn’t the smartest way of checking if the object is null or not specially when you are dealing with strings.
Many people recommend doing it differently, like combing it with && for some property check of that object, it would look like this,
//this is standard way of finding if the objects are null or not
//since the object is initialized there should not be a trace
//ofcourse since this is string i am testing for length.
if (!strObj && strObj.length){
trace("this shouldn't be happening");
}
Just something to keep in mind, its not always necessary.
why not:
strobj != null
?
duh…. for some reason tht thought never occurred to me ….. 😮