AS3: NaN as Nullable Numbers

by troy on September 23, 2007

One major change from AS2 was the removal of Numbers being nullable, this was useful for determining if something had been given a value or not, and setting it to a default. One workaround is using NaN, which can be used on the function initializer:

function testNum(num:Number = NaN) {
if (isNaN(num)) {
trace(num + " no num");
} else {
trace("has num: " + num);
}
}
 
/////////// BEGIN TEST /////////////
var numA:Number; //NaN
 
testNum(); // NaN no num
testNum(numA); //NaN no num
numA = -1;
testNum(numA); //has num: -1
numA = 0;
testNum(numA); //has num: 0
numA = 1;
testNum(numA); //has num: 1

Leave a Comment

Previous post:

Next post: