Main Page

Boolean class

The Boolean class
The
Boolean
class is the reference type for the Boolean primitive type. To create a
Boolean
object, you
need only pass in a Boolean value as a parameter:
var oBooleanaobject = new Boolean(true);
Boolean
objects override the
valueOf()
method of the
Object
class to return a primitive value of
either
true
or
false
; the
toString()
method is also overridden to return a string of “
true”
or
“false”
when called. Unfortunately, not only are Boolean objects of little use in ECMAScript, they can
actually be rather confusing.
The problem typically occurs when trying to use
Boolean
objects in Boolean expressions. For example:
var oFalseObject = new Boolean(false);
var bResult = oFalseObject && true; //outputs true
In this code, a
Boolean
object is created with a value of
false
. That same object is then ANDed with
the primitive value
true
. In Boolean math,
false
AND
true
is equal to
false
. However, in this line of
code it is the
oFalseObject
being evaluated, not its value (
false
). As discussed earlier, all objects are
automatically converted to
true
in Boolean expressions, so
oFalseObject
actually is given a value of
true
in the expression. Then,
true
ANDed with
true
is equal to
true
.
The Number class
As you might have assumed, the
Number
class is the reference type for the Number primitive type. To
create a
Number
object, do the following:
var oNumberObject = new Number(55);
You may recognize the
Number
class from earlier in this chapter, where the special number values are
discussed (such as
Number.MAX_VALUE
). All the special values are static properties of the
Number
class.
To get the Number primitive value for a number object, simply use the
valueOf()
method:
var iNumber = oNumberObject.valueOf();
Of course, the
Number
class also has a
toString()
method, which was discussed at length in the section
on conversions. Aside from the standard methods inherited from the
Object
class, the
Number
class has
several methods specifically for working with number values.
Although you should understand that the
Boolean
object is available, it’s best to use
Boolean primitives only to avoid the problems mentioned in this section.
27
ECMAScript Basics
05_579088 ch02.qxd 3/28/05 11:35 AM Page 27


JavaScript EditorFree JavaScript Editor     Ajax Editor


©

R7