Special Numbers, Null and Undefined

There are less obvious primitive types and values as well. These are the three special Number values Infinity, -Infinity and NaN. There are also the special types Null and Undefined.

The three special Number values can't be used as constants, so there is no way to type them in, but there are variables called NaN and Infinity which contain these special values, so those variables can be used where these values are needed. NaN means 'Not a Number' and is the result of a mathematical operation that makes no sense. The Null type has only one value, null. Null means 'no data'—it's used as a placeholder in a variable to let you know there's nothing useful in there. The Undefined type is trickier. It also has one value: undefined, which is often the same as null. If a variable's contents are unclear, because nothing (not even null) has ever been stored in it, then it's undefined, but for convenience, much of the time it acts as if it had a null value. Unless you are doing something advanced, undefined is usually bad news meaning your script isn't working properly. In the example above, variable new_value is undefined because nothing is ever assigned to it. So is the variable old_value, because it doesn't appear at all. The safest way to examine these special values is with some special utilities—isNaN(), isFinite() and typeof()—described later.

The NaN and Infinity variables may be standard, but they are too new for all but the most recently released browsers. You can create them yourself if you want to stick close to the standard in your scripts. Here's how:

var NaN = 0/0;
var Infinity = 1e300 * 1e300;

There are two widely available constants that can be used to check infinite values. They are Number.POSITIVE_INFINITY and Number.NEGATIVE_INFINITY. See the section below on Objects, and the Reference Section.

Don't rely on the special values printing out the same on all browsers, and don't do mathematics with these values if you're going to create them, as results can be unpredictable. Internet Explorer 3.02 with JScript 1.0 has no idea about NaN, it just silently converts to 0 (zero). You can't tell the difference between undefined and null using Netscape Navigator 2.02, and it doesn't understand Number.POSITIVE_INFINITY or Number.NEGATIVE_INFINITY either. It is not until browser version 4.0 that NaN is highly bug-free.

© 1997 by Wrox Press. All rights reserved.