ActionScript Emptiness

I’m a great believer that if you’re going to be good at something you should understand it a the lowest level possible. Every ActionScript developer I talk to at the moment is migrating to AS3 and mostly we talk about all the high level differences it has with AS2; the API, the event mechanism and so forth. But let’s not forget the little things. It’s often complacency toward the smallest components that cause the most trouble. It seems like an odd situation to know how to flip a cube around in 3D space, but not really know the difference between null and undefined. This is a real situation though, and it can mean bugs deep in complex layers of code just waiting to ruin everything.

So in this spirit of pedanticalness I’ve been playing around with the various changes to the null, and undefined types in AS3 and how they relate to the new concept of untyped objects. Having been writing JavaScript and ActionScript for years these notions are taking some getting used to. That’s fine, but I have noticed some nuances that I’m not happy with.

I’m fine with the notion that a typed object cannot contain the value undefined. It makes sense that it should adopt a native value of its own. I do find it strange though that a Number defaults to NaN, whereas int, and uint default to 0, but I think I’ll just about sleep at night.

I also find it odd that some typed objects may be set to null, while some cannot. (var s:String = null;) holds null and is still a String, and yet: (var n:Number = null;) raises an error. Although I don’t really get this, being aware of it is the important thing when it comes to avoiding bugs.

Here are some more weird things I discovered today:
Setting a Number to null via a function call prevents the error you get when setting it directly.

  1. function getNull():* { 
  2.     return null; 
  3. } 
  4. trace( getNull() === null); // prints “true” 
  5. var x:Number = null; // raises error 
  6. var y:Number = getNull(); // no error   

Setting a Number to undefined via a void function call raises an error

  1. function getUndefined():void{ 
  2.     // no return value. 
  3. } 
  4. trace( getUndefined() === undefined ); // prints “true” 
  5. var x:Number = undefined; // sets to NaN as expected 
  6. var n:Number = getUndefined(); // raises error, halts execution

Hmm..