Полезная информация

JavaScript: The Definitive Guide

Previous Chapter 3
Variables and Data Types
Next
 

3.9 Undefined

There is another special value occasionally used by JavaScript. This is the "undefined" value returned when you use a variable that doesn't exist, or a variable that has been declared, but never had a value assigned to it, or an object property that doesn't exist.

Unlike the null value, there is no undefined keyword for the undefined value. This can make it hard to write JavaScript code that detects this undefined value. The undefined value is not the same as null, but for most practical purposes, you can treat it as if it is. This is because the undefined value compares equal to null. That is, if we write:

my.prop == null
the comparison will be true both if the my.prop property doesn't exist, or if it does exist but contains the value null.

In Navigator 3.0 and later, you can distinguish between null and the undefined value with the typeof operator (which is discussed in detail in Chapter 4, Expressions and Operators). This operator returns a string that indicates the data type of any value. We said above that null is actually a object value, and when we use typeof on null, it indicates this by returning the string "object":

type = typeof null;                   // returns "object"
However, when we apply typeof to a variable that has had no value assigned (or to an undefined variable or property), it returns the string "undefined":

var new_undefined_variable;
type = typeof new_undefined_variable  // returns "undefined"
The implication of this "undefined" result is interesting. It means that the undefined value is a completely different data type than any other value in JavaScript.


Previous Home Next
Null Book Index The Date Object

HTML: The Definitive Guide CGI Programming JavaScript: The Definitive Guide Programming Perl WebMaster in a Nutshell