Main Page

The Null type

alert(typeof oTemp); //outputs “undefined”
alert(typeof oTemp2); //outputs “undefined”
The previous code outputs
“undefined”
for both variables, even though only one of them (
oTemp2
) is
undefined. If you try to use
oTemp2
with any operator other than
typeof
, it causes an error because
operators can only be applied to defined variables. For example, this causes an error:
//make sure this variable isn’t defined
//var oTemp2;
//try outputting
alert(oTemp2 == undefined); //causes error
The value
undefined
is also returned when a function doesn’t explicitly return a value, as in the
following:
function testFunc() {
//leave the function blank
}
alert(testFunc() == undefined); //outputs “true”
The Null type
Another type with just one value, the Null type, has only the special value
null
, which is also its literal.
The value
undefined
is actually a derivative of the value
null
, so ECMAScript defines them as equal to
each other.
alert(null == undefined); //outputs “true”
Even though the values are both true, they are considered to have different meanings. Whereas
undefined
is the value assigned when a variable is declared and not initialized,
null
is the value used
to represent an object that doesn’t exist (which I touched upon briefly in the discussion of the
typeof
operator). If a function or method is supposed to return an object, it usually returns
null
when the
object isn’t found.
The Boolean type
The Boolean type is one of the most frequently used in the language. It has two values,
true
and
false
(which are also the two Boolean literals). Even though
false
isn’t equal to
0
,
0
is converted to
false
when necessary, making it safe to use either in a Boolean statement.
var bFound = true;
var bLost = false;
The Number type
The most unique type defined in ECMA-262 is the Number type. The Number type can represent both
32-bit integer and 64-bit floating-point values. A Number type literal is considered any number entered
18
Chapter 2
05_579088 ch02.qxd 3/28/05 11:35 AM Page 18


JavaScript EditorFree JavaScript Editor     Ajax Editor


©

R7