Monday, January 2, 2012

Undefined=5

One day, I shall write a JavaScript library and include this line in it:
var undefined = 5
For those of you JavaScript buffs, you must have realized that this will break almost every sufficiently large JavaScript code in eternity without causing any compiler errors.

For those of you who don't know JS, take the time to learn it! It’s actually quite fun to learn.

And the reason why the code will break it is simple, if not a bit weird:
JS has two types of null values: null and undefined. Null is an actual object, kinda like NaN. You can call it and have no problems. Undefined, on the other hand, is nothing (not even a keyword). I can even type undefined=2 and have no errors. Now, JS, with the == operator, can't distinguish between the two. As in, window.blahblah==null returns true even if window.blahblah is not defined . But, JS has a wonderfully quirky operator known as the identity operator. This guy can tell the difference between null and undefined. Eg:
var poopy //gets a psuedo-default value "undefined"
return poopy===null //Will return false. Poopy is not null, it is undefined
It will only return true if you type poopy=null at the top. The reason for this is that == compares objects, typecasting them if necessary (so undefined is typecasted to null), while === preserves type and compares.

Now, as I showed, using window.blahblah==null won't tell you if the property is deliberately set to null or just not defined. Unfortunately, when developing frameworks which fit into larger applications, you don't have control over the rest of the code, but you still have to interact with it. Which means checking for undefined values becomes crucial. In that case, most people do this:
var undefined; //declare a variable which is not initialized
return poopy===undefined // check if poopy is in the same state as the undefined variable, i.e. uninitialized
This would work even if I didn't call the variable undefined:
var bloopy
return poopy===bloopy
But, JS programmers are obstinate fellows who always use the first method.
Now, if I type var undefined=5 in a JavaScript framework, all other code which uses the above trick won't work. Why? Now, the variable "undefined" is no longer undefined (i.e. uninitialized), and the program returns the exact opposite value that it should. Since checking for undefined values is quite essential in asynchronous scripting, this can make the scripts do unexpected things.

Kablooey.

PS: If anyone here is working on a large framework, please, please type var undefined=5 somewhere in the code. And make sure your code doesn't use undefined for checking for initialization. There you have it. Your code will be the only one that works when combined with other (sufficiently large) code.
Neat, huh?

No comments:

Post a Comment