JavaScript tutorial:
Data type conversion

 

JavaScript provides automatic type conversion as the context may require. This means that if the context expects a value to be a string, for example, JavaScript tries to convert the value to a string.

The language has six types of data. All values have one of these types:

undefined

The undefined type has one value only, undefined.

Null

The null type has one value only, null.

Boolean

The Boolean type represents the two logical values, true and false.

String

Strings, delineated by single or double quotation marks, contain zero or more Unicode characters. An empty string ("") has zero characters and length.

 

Number

Numbers can be integers or floating-point numbers according to the IEEE 754 specification. There also several special values:

    • NaN, or not a Number

    • Positive Infinity

    • Negative Infinity

    • Positive zero

    • Negative zero

Object

An Object type is an object definition including its set of properties and methods.

The following table defines what happens when the context requires that JavaScript convert one data type into another:

 

Output Data Type

Input Data Type

Undefined

Null         

Boolean

Number

String

Object

boolean

false

false

no conversion

false if +0, -0, or NaN; otherwise true

false if empty string (""); otherwise true

true

number

NaN

NaN

1 if true; +0 if false

no conversion

If it cannot be interpreted as a number, it is interpreted as NaN

Number object

string

"undefined"

"null"

"true" or "false"

The absolute value of the number plus its sign, with the following exceptions:

  • NaN returns "NaN"

  • +0 or -0 returns "0"

  • + infinity returns "Infinity"

  • - infinity returns "-Infinity"

  • no conversion

    String object

    object

    run-time error

    run-time error

    New Boolean object

    New Number object

    New String object

    no conversion