if (x!=x) console.log("Wahay!");
A while back I posed a little JavaScript question: When would the above JavaScript statement print “Wahay"?
This provoked a storm of apathy on the internet, but I’m going to tell you the answer anyway. You use the above test to detect a variable which is not a number (NaN).
JavaScript is a bit strange when it comes to handling errors.
x = 1/"fred";
Some languages would not even compile the above statement. Some languages would stop the program at this statement. JavaScript does something different. It says “Dividing a number by a string is silly, I’m going to set the value of x to a special value which means “Not a number”. JavaScript has other special values too. If you divide any number by 0 you get a special value called Infinity, which behaves like infinity. Add a number to infinity and you get infinity as a result. Divide any number by infinity and you get zero. Divide infinity by infiniuty and you get Not a Number - which is also right.
But I digress. What would the statement at the top do? Well, it is how you test for Not a Number in a JavaScript program. Suppose you want to check if x contains NaN. You might think that you do this:
if (x==NaN) console.log("Not a number!");
However, this statement will not work, because something which is not a number is not equal to anything, including NaN. So the test always fails. Which is why you sometimes see NaN in JavaScript forms because the programmer didn’t know this or test it.
However, a value which is not a number isn’t even equal to itself, which is why the test is so useful.