Tuesday, April 21, 2009

Number and NaN

What is the output of the following code?
var n1:Number = null;
var n2:Number;
trace(n1);
trace(n2);
I have Java background, so the whole NaN concept still confuses me sometimes. I would have expected that assigning null to a Number would be the same as not assigning anything to the Number. But no! When you assign n1 to null, it actually is the same as assigning it the value 0! Although the Flex compiler will actually give you a warning if you try this. If you leave a Number unassigned like n2, then it has the value NaN. Or if you try to cast a String or Object into a Number and it fails then the Number will also be NaN.

And one last note - don't set the horizontalGap or verticalGap (or any other style used by layouts) to NaN otherwise the BoxLayout will not work at all. Took me a while to figure out why my VBox wasn't laying out all the components properly!

No comments: