HTML and CSS Reference
In-Depth Information
Figure 3.2 Output from Example 3.3.
Null and Undefined . The difference between null and undefined is a little subtle.
The null keyword represents “no value,” meaning “nothing,” not even an empty string
or zero. It is a type of JavaScript object (see Chapter 8, “Objects”). It can be used to ini-
tialize a variable so that it does not produce errors or to clear the value of a variable, so
that there is no longer any data associated with that variable, and the memory used by
it is freed. When a variable is assigned null , it does not contain any valid data type.
A variable that has been declared, but given no initial value, contains the value unde-
fined and will produce a runtime error if you try to use it. (If you declare the variable
and assign null to it, null will act as a placeholder and you will not get an error.) The
word undefined is not a keyword in JavaScript. If compared with the == equality opera-
tors, null and undefined are equal, but if compared with the identity operator, they are
not identical (see Chapter 5, “Operators”).
EXAMPLE 3.4
<html>
<head>
<title>The typeof Operator with Null and Undefined</title>
</head>
<body bgColor="gold">
<big>
<script type="text/javascript">
document.write("<em>null</em> is type "+
1
typeof(null) ,"<br />");
document.write("<em>undefined</em> is type "+
2
typeof(undefined) ,"<br />");
</script>
</big>
</body>
</html>
EXPLANATION
1
The null keyword is a type of object. It is a built-in JavaScript object that contains
no value.
2
Undefined is returned when a variable has been given no initial value or when the
void operator is used (see Table 5.19 on page 120). See output in Figure 3.3.
 
Search WWH ::




Custom Search