Wednesday 16 February 2011

Flex, ActionScript 3, How to Handle the... NaN (Not a No-brainer)

situation
In ActionScript 3, you can no longer assign null to specific native data types. If you try to do this with 'Number' for example you'll receive a warning that 'null used where Number type expected'. Take the following code snippet for example:
var MyNumber:Number;

MyNumber = getNumber();
if (MyNumber == null)
{
// do something
}

If you try to return 'null' from the getNumber() method you'll receive the aforementioned warning.

Although this is only a compiler warning, perhaps the better way to handle this is to have getNumber return NaN (and make the comparison against NaN) since in ActionScript 3 the default value of the Number data type is now 'NaN'(Not a Number). This leaves us with this:
var MyNumber:Number;

MyNumber = getNumber();
if (MyNumber == NaN)
{
// do something
}


problem
But NaN is a funny kind of beast in ActionScript. If you tried to code things like they are above, you would receive another compiler warning, 'illogical comparison with NaN. This statement always returns false'. Any comparsion with NaN returns false in fact, suprisingly, even this one:
if (NaN == NaN)
{
}


solution
Your best bet is to never deal with NaN directly but instead use the built in isNaN function to correctly evaluate whether your variable is not a number.
var MyNumber:Number;

MyNumber = getNumber();
if (isNaN(MyNumber))
{
// do something
}

No comments:

Post a Comment