AJAX - The Complete Reference

(avery) #1

PART IV


Appendix A: JavaScript Quick Reference 557


Type Conversion

Type conversion is automatically carried out in JavaScript. Table A-6 shows the common
conversion rules when data is automatically converted to one type or another. Automatic
conversion happens very often when using relational operators discussed later in the
section. It is also possible to force type conversion using a variety of built-in methods
summarized in Table A-7.

Value

Convert to
Boolean

Convert to
Number Convert to String Convert to Object
true 1 "true" Boolean object with
value of true
false 0 "false" Boolean object with
value of false
0 false "0" Number object with
value of 0
Any nonzero
number including
negative
numbers

true The number as
a string, so 40
becomes “40”
while −1.13
becomes "−1.13"

Number object of
the value indicated

Empty string "" false 0 String object with
no value
A nonempty
string

true

This means
that strings like
“0” and “false”
convert to true
as well.

If the string
contains solely
a number like
"4" it will be
converted into
the number. All
other strings will
be converted to
NaN. Note that
strings must
strictly contain
a number for
conversion for
example, "4no"
converts to NaN
and not 4.

String object
containing the string
primitive value

Any existing
object

true NaN Value of
toString()
method of the
object
null false 0 "null" TypeError Exception
thrown
undefined false NaN "undefined" TypeError Exception
thrown

TABLE A-6 Primitive JavaScript Data Types
Free download pdf