DekGenius.com
Team LiB   Previous Section   Next Section

3.8 undefined

Another special value used occasionally by JavaScript is the undefined value returned when you use either a variable that has been declared but never had a value assigned to it, or an object property that does not exist. Note that this special undefined value is not the same as null.

Although null and the undefined value are distinct, the == equality operator considers them to be equal to one another. Consider the following:

my.prop == null 

This comparison is true either if the my.prop property does not exist or if it does exist but contains the value null. Since both null and the undefined value indicate an absence of value, this equality is often what we want. However, if you truly must distinguish between a null value and an undefined value, use the === identity operator or the typeof operator (see Chapter 5 for details).

Unlike null, undefined is not a reserved word in JavaScript. The ECMAScript v3 standard specifies that there is always a global variable named undefined whose initial value is the undefined value. Thus, in a conforming implementation, you can treat undefined as a keyword, as long as you don't assign a value to the variable.

If you are not sure that your implementation has the undefined variable, you can simply declare your own:

var undefined; 

By declaring but not initializing the variable, you assure that it has the undefined value. The void operator (see Chapter 5) provides another way to obtain the undefined value.

    Team LiB   Previous Section   Next Section