Oct 12, 2008

undefined, null and boolean comparisons in Javascript

Last week I've been working with some simple javascript and I found a common mistake when someone tries to use a variable into an if() or for() sentence.
First let's make a simple review about types in javascript:

Javascript has 5 primitive data types: string, boolean, number, null and undefined.

The first three types are well-known types. Let's talk a bit about the others; undefined means that a variable has been declared but it has not yet been assigned to a value, null is representative for an object that has not been initialized.
In fact, undefined is a type in itself and null is an object.
Consider this example:


var undef;
var nullObject = null;

alert(undef); //shows "undefined"
alert(nullObj); //shows "null"

if(undef) // always false;
if(nullObject) //always false;

Now what if I use an undefined in comparison with a number?


if(1 > undef) //false
if(1 < undef) //false
if(1 == undef) //false


So, nice! don't you think? The problem that I found was into a for sentence, doing something like this:


var flag = true;

for(var i = 0 ; i < someVar || flag ; i++){
   if(someVar < 1) flag = false;
   //some code goes here ...
}

This code has no much sense, but it is for simple demonstration purpose, think about it for a moment.

Looks like a simple, nice and unoffensive javascript code right? No, this is an infinit loop, since undefined < 1 is always false.

Conclusion:
if you are trying to obtain some data maybe using something like document.getElementById() or whatever function which can retrieves an undefined, take this into account.

Enjoy!
elmasse!