↑
Main Page
String type
A few special values are also defined as part of the Number type. The first two are
Number.MAX_VALUE
and
Number.MIN_VALUE
, which define the outer bounds of the Number value set. All ECMAScript
numbers must fall between these two values, without exception. A calculation can, however, result in
a number that does not fall in between these two numbers.
When a calculation results in a number greater than
Number.MAX_VALUE
, it is assigned a value of
Number.POSITIVE_INFINITY
, meaning that it has no numeric value anymore. Likewise a calculation
that results in a number less than
Number.MIN_VALUE
is assigned a value of
Number.NEGATIVE_
INFINITY
, which also has no numeric value. If a calculation returns an infinite value, the result cannot
be used in any further calculations.
There is actually a special value for infinity named (you guessed it)
Infinity
.
Number.POSITIVE_
INFINITY
has a value of
Infinity
, whereas
Number.NEGATIVE_INFINITY
has a value of
–Infinity
.
Because an infinite number can be positive or negative, a method can be used to determine if a number
is finite (instead of testing for each infinite number separately). The
isFinite()
method can be called
on any number to ensure that the number isn’t infinite. For example:
var iResult = iNum* some_really_large_number;
if (isFinite(iResult)) {
alert(“Number is finite.”);
} else {
alert(“Number is infinite.”);
}
The final special number value is
NaN
, which stands for
Not a Number
.
NaN
is an odd special value. In
general, this occurs when conversion from another type (String, Boolean, and so on) fails. For example,
trying to convert the word
blue
into a number value will fail because there is no numeric equivalent. Just
like the infinity values,
NaN
cannot be used in mathematical calculations. Another oddity of
NaN
is that it
is not equal to itself, meaning that the following will return
false
:
alert(NaN == NaN); //outputs “false”
For this reason, it is not recommended to use the
NaN
value itself. Instead, the function
isNaN()
will do
the job quite nicely:
alert(isNaN(“blue”)); //outputs “true”
alert(isNaN(“123”)); //outputs “false”
The String type
The String type is unique in that it is the only primitive type that doesn’t have a definite size. A string
can be used to store zero or more Unicode characters, represented by 16-bit integers (Unicode is an inter-
national character set that is discussed later in this book).
Each character in a string is given a position, starting with the first character in position 0, the second
character in position 1, and so on. This means that the position of the final character in a string is always
the length of the string minus 1 (see Figure 2-2).
20
Chapter 2
05_579088 ch02.qxd 3/28/05 11:35 AM Page 20
Free JavaScript Editor
Ajax Editor
©
→