Groups | Blog | Home
all groups > flash actionscript > may 2007 >

flash actionscript : Determining if a Variable is defined with if statement.


OrangeHaze
5/25/2007 11:24:44 PM
Hello, I'm interested in anyone knows if it is bad practice to check if a value
has been defined using this method...

if(!myVar)
trace("myVar is not defined)

it should be equivalent to ...

if(myVar == undefined)
trace("myVar is not defined)

I'm aware that the first method might not be as clear (e.g. someone might
immediately think that myVar is a Boolean), but I have been using this method
to check if a variable exists, or is undefined for some time now, and have not
encountered any problems. However, if there is something wrong with it I would
like to adopt the best practice, especially when transitioning to AS3.
kglad
5/25/2007 11:49:52 PM
there's nothing wrong as long as you realize that myVar may be defined and
!myVar could resolve to true (when myVar is 0 or is false) in as 2.

in as 3, the compiler will throw an error if you attempt to access an
undefined variable unless you cast the variable as the property of a dynamic
class.
Trevor McCauley - Adobe
5/26/2007 6:07:10 AM
In AS3 you have a different way of handling variables. Not all variables
are given the same default values if declared and not defined. Normally you
would think this to be 'undefined' but with AS3 you'll get:
var untyped:*; // (or no typing) undefined
var boolean:Boolean; // false
var number:Number; // NaN
var integer:int; // 0
var unsignedInteger:uint; // 0
var string:String; // null
var object:Object; // nulland all other objects also being null. Undeclared
variables will only work in dynamic classes (like MovieClip) and will be
undefined. Otherwise, every variable has to be declared with var to be used
at all. If no value is given to them then, their values will match those
above (or if any other object type, be null).

When checking them, a non-strict equality (==) should be mostly fine for
null values, though its possble AS3 will complain. Your best bet is to just
use null. For Number types you have to use isNaN() (comparing == NaN will
not work) and for Boolean, int and uint numeric types, there's no way to
tell since their default values are real values that those types can be used
for. Sometimes, for uint, you can get away with using an int instead
(depending on your circumstances) and default its value to -1. Then, you'll
know the value hasn't been initialized being less than 0.



[quoted text, click to view]

AddThis Social Bookmark Button