↑
Main Page
The Undefined type
var sTemp = “test string”;
alert(typeof sTemp); //outputs “string”
alert(typeof 95); //outputs “number”
Calling
typeof
on a variable or value returns one of the following values:
?
“undefined”
if the variable is of the Undefined type.
?
“boolean”
if the variable is of the Boolean type.
?
“number”
if the variable is of the Number type.
?
“string”
if the variable is of the String type.
?
“object”
if the variable is of a reference type or of the Null type.
The Undefined type
As previously mentioned, the Undefined type has only one value,
undefined
. When a variable is
declared and not initialized, it is given the value of
undefined
by default.
var oTemp;
The previous line of code declares a variable named
oTemp
, which has no initialization value. This vari-
able is given a value of
undefined
, which is the literal representation of the Undefined type. You can
test that the variable is equal to the literal yourself by running this code snippet:
var oTemp;
alert(oTemp == undefined);
This code displays an alert with the word
“true”
, indicating that these two values are indeed equal.
You can also use the
typeof
operator to show that the variable has a value of
undefined
.
var oTemp;
alert(typeof oTemp); //outputs “undefined”
Note that a variable having the value of
undefined
is different from a value being undefined. However,
the
typeof
operator doesn’t actually distinguish between the two. Consider the following:
var oTemp;
//make sure this variable isn’t defined
//var oTemp2;
//try outputting
You may wonder why the
typeof
operator returns “object” for a value that is
null
.
This was actually an error in the original JavaScript implementation that was then
copied in ECMAScript. Today, it is rationalized that
null
is considered a place-
holder for an object, even though, technically, it is a primitive value.
17
ECMAScript Basics
05_579088 ch02.qxd 3/28/05 11:35 AM Page 17
Free JavaScript Editor
Ajax Editor
©
→