LA.NET [EN]

Sep 02

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.

2 comments so far

  1. Bertrand Le Roy
    12:04 am - 9-3-2009
  2. luisabreu
    12:28 pm - 9-3-2009

    Yes, lots of fun :)

Leave a Reply

Your email address will not be published. Required fields are marked *


*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>