Don’t change NaN and undefined values

One thing most people don’t know is that they NaN and undefined are just global variables. Don’t believe me? Ok, run the following snippets:

var initialNaN = NaN;
NaN = 10;
alert(NaN === 10);
alert(initialNaN === 10);

I can tell you that the first time someone showed me a similar example I just thought “WTF is going on here?”. There are other problems you’ll probably trip on when you start using NaN. For instance, I’ve seen code that looks like this in the past:

var something = 10;
if (something === NaN) {
    alert("oopss");
}
//more code here
//and then you end up getting NaN somehow
something = NaN;
if (something === NaN) {
    alert("oops2");
}

What will happen when you run the previous snippet? If you’re thinking you’ll be seeing an alert message with the text “oops2”, you’re wrong. The reason is simple: you cannot use the === operator to compare a value with NaN because NaN isn’t  equal to itself. In other words, NaN === NaN will always return false and NaN !== NaN will always return true. Not cool, but that’s just the way it is.

Btw, the correct way to check for the NaN value is to use the isNaN helper function. Here’s the updated snippet that produces the expected  results:

var something = 10;
if (isNaN(something)) {
    alert("oopss");
}
//more code here
//and then you end up getting NaN
something = NaN;
if (isNaN(something)) {
    alert("oops2");
}

And that’s it for today. Keep tuned for more on JavaScript.

Advertisements

~ by Luis Abreu on September 2, 2009.

2 Responses to “Don’t change NaN and undefined values”

  1. Ah yes, take a look at those:
    http://weblogs.asp.net/bleroy/archive/2006/06/28/NaN-is-a-number.aspx
    http://weblogs.asp.net/bleroy/archive/2006/08/02/Define-undefined.aspx
    Fun stuff!

  2. Yes, lots of fun 🙂

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: