AS3 undefined vs null

Believe it or not, there’s a difference between undefined and null. It may seem redundant to have two constants that represent invalid values/variables, but given the dynamic nature of the ActionScript language, their existence is pretty evident. If you don’t believe me, try the code below.

[as3]
trace(null == undefined); //Outputs true
trace(null === undefined); //Outputs false
[/as3]

ActionScript along with JavaScript are weakly typed languages, though ActionScript 3 is stricter than JavaScript and all of its predicesors, it’s still weak/loose/duck typed. ActionScript 3 is like that crazy cousin we all have that never played by the rules and Flashed everyone off! OK, all pun aside, the * type – or the “untyped” type – can cast anything as anything, which is why ActionScript 3 is still not as strict as say, C++ or JAVA.

[as3]
var i:* = {};
i = 7.4;
i = “11”
i = new iClass();
//All these are fine as i is an untyped(*) variable.
[/as3]

Another reason for why ActionScript 3 is still not a truly Nun/strictly typed language is its ability to create objects, classes and associative arrays on the fly. Consider the following code.

[as3]
var i:Object = [];
i.push({a:”b”, c:4}, 123, new Dictionary());
trace(i); //Outputs [object Object],123,[object Dictionary]
[/as3]

Belonging to the family of ECMA languages, its purpose is obvious. It serves as a Front-End technology to run on the client and when compared with JavaScript it runs in a plug-in compiled to bite-code as apposed to compilation onLoad then execution, but that’s a different topic…

To a logical mind, there is only one nothing, or null value. But undefined holds a very special place in the hearts of front end development. Say you’re loading a feed from some web-service out there on the “internets”, and you’re not quite sure what to expect, this is a common scenario where undefined would come into play. There are tons of techniques on how to handle similar situations, but if you want to preserve the integrity of your run-time constants, simply checking against an empty String isn’t the best of practices.

Code Explained

NULL: In this example, the variable “i” is null, as it has not yet been instantiated with any values. This is a common occurrence when we create new classes with all their corresponding properties but forget to associate them with any value.

[as3]
var i:Object;
trace(i); //Outputs null
i = {};
trace(i); //Outputs [object Object]
[/as3]

UNDEFINED: In this example, the property “e” of variable “i” is undefined, as “e” has not yet been instantiated.

[as3]
var i:Object = {a:”b”, c:”d”};
trace(i.e); //Outputs undefined
i.e = “f”;
trace(i.e); //Outputs f
[/as3]

It’s worth noting that back in ActionScript 2, null didn’t exist. So simply declaring and not instantiating a variable wouldn’t result in an undefined.

This entry was posted in Flash AS3, Syntax and tagged , , , . Bookmark the permalink.