Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

JavaScript Type Conversion

JavaScript Type Conversion


Number() converts to a number, String() converts to a string, Boolean() converts to a boolean.


JavaScript Data Types

There are 6 different data types in JavaScript:

3 object types:

2 data types that contain no value:


The typeof operator

You can use the typeof Use the operator to check the data type of a JavaScript variable.

Example

typeof

"John"

                

// returns string

typeof

3.14

                  

// returns number

typeof

NaN                   

// returns number

typeof

false

                 

// returns boolean

typeof

[

1

,

2

,

3

,

4

]              

// returns object

typeof

{name:

'John'

, age:34} 

// returns object

typeof

new

Date()            

// returns object

typeof

function

() {}        

// returns function

typeof

myCar                 

// returns undefined (if myCar was not declared)

typeof

null

                  

// returns object

Try it »

Please note:

If an object is a JavaScript Array or a JavaScript Date, we cannot determine their type through typeof because both return object.


The constructor property

constructor The property returns the constructor function of all JavaScript variables.

Example

"John"

.constructor                

// returns the function String() { [native code] }

(

3.14

).constructor                

// returns the function Number() { [native code] }

false.constructor                 

// returns the function Boolean() { [native code] }

[

1

,

2

,

3

,

4

].constructor             

// returns the function Array() { [native code] }

{name:

'John'

, age:34}.constructor 

// returns the function Object() { [native code] }

new

Date().constructor            

// returns the function Date() { [native code] }

function

() {}.constructor        

// returns the function Function(){ [native code] }

Try it »

You can use the constructor property to check whether an object is an array (contains the string "Array"):

Example

function

isArray(myArray) {

   

return

myArray.constructor.toString().indexOf(

"Array"

) >

-1

;

}

Try it »

You can use the constructor property to check whether an object is a Date (contains the string "Date"):

Example

function

isDate(myDate) {

   

return

myDate.constructor.toString().indexOf(

"Date"

) >

-1

;

}

Try it »


JavaScript Type Conversion

JavaScript variables can be converted to new variables or other data types:


Convert a number to a string

Global methods String() Can convert numbers to strings.

This method can be used with any type of number, letter, variable, or expression:

Example

String(x)         

// converts the variable x to a string and returns it

String(

123

)      

// converts the number 123 to a string and returns it

String(

100

23

) 

// converts a numeric expression to a string and returns it

Try it »

Number methods toString() has the same effect.

Example

x.toString()

(

123

).toString()

(

100

23

).toString()

Try it »

in Number methods In the chapter, you can find more methods for converting numbers to strings:

Method Description
toExponential() Converts the value of an object to exponential notation.
toFixed() Converts a number to a string with a specified number of digits after the decimal point.
toPrecision() Formats a number to a specified length.

Converting booleans to strings

Global methods String() Can convert booleans to strings.

String(

false

)       

// returns "false"

String(

true

)        

// returns "true"

Boolean methods toString() have the same effect.

false.toString()    

// returns "false"

true.toString()     

// returns "true"


Converting dates to strings

Date() returns a string.

Date()     

// returns Thu Jul 17 2014 15:38:19 GMT+0200 (W. Europe Daylight Time)

The global method String() can convert a Date object to a string.

String(new Date())     

// returns Thu Jul 17 2014 15:38:19 GMT+0200 (W. Europe Daylight Time)

Date methods toString() have the same effect.

Example

obj = new Date()

obj.toString()  

// returns Thu Jul 17 2014 15:38:19 GMT+0200 (W. Europe Daylight Time)

in Date methods In the chapter, you can see more functions about converting dates to strings:

Method Description
getDate() Returns the day of the month (1 ~ 31) from a Date object.
getDay() Returns the day of the week (0 ~ 6) from a Date object.
getFullYear() Returns the year from a Date object as a four-digit number.
getHours() Returns the hour of the Date object (0 ~ 23).
getMilliseconds() Returns the milliseconds of the Date object (0 ~ 999).
getMinutes() Returns the minutes of the Date object (0 ~ 59).
getMonth() Returns the month from a Date object (0 ~ 11).
getSeconds() Returns the seconds of the Date object (0 ~ 59).
getTime() Returns the number of milliseconds since January 1, 1970.

Convert a string to a number

Global methods Number() Can convert strings to numbers.

A string containing a number (such as "3.14") converts to a number (such as 3.14).

An empty string converts to 0.

Other strings convert to NaN (not a number).

Number(

"3.14"

)   

// returns 3.14

Number(

" "

)      

// returns 0

Number(

""

)       

// returns 0

Number(

"99 88"

)  

// returns NaN

in Number methods In the chapter, you can see more methods for converting strings to numbers:

Method Description
parseFloat() Parses a string and returns a floating-point number.
parseInt() Parses a string and returns an integer.

The unary operator +

The **Operator + ** can be used to convert a variable to a number:

Example

var

y =

"5"

;     

// y is a string

var

x = + y;     

// x is a number

Try it »

If the variable cannot be converted, it will still be a number, but with the value NaN (not a number):

Example

var

y =

"John"

;  

// y is a string

var

x = + y;      

// x is a number (NaN)

Try it »


Converting booleans to numbers

Global methods Number() Can convert booleans to numbers.

Number(

false

)    

// returns 0

Number(

true

)     

// returns 1


Converting dates to numbers

Global methods Number() Can convert dates to numbers.

d =

new

Date();

Number(d)         

// returns 1404568027739

Date methods getTime() have the same effect.

d =

new

Date();

d.getTime()       

// returns 1404568027739


Automatic type conversion

When JavaScript tries to operate on a "wrong" data type, it automatically converts to the "correct" data type.

The following outputs are not what you might expect:

5

null

   

// returns 5 null converted to 0

"5"

null

 

// returns "5null" null converted to "null"

"5"

1

   

// returns "51" 1 converted to "1" 

"5"

1

    

// returns 4 "5" converted to 5


Automatic conversion to strings

When you try to output an object or a variable, JavaScript automatically calls the variable's toString() method:

document.getElementById(

"demo"

).innerHTML = myVar;

myVar = {name:"Fjohn"} // toString converts to "[object Object]"

myVar = [1,2,3,4] // toString converts to "1,2,3,4"

myVar = new Date() // toString converts to "Fri Jul 18 2014 09:08:55 GMT+0200"

Numbers and booleans are also often converted to each other:

myVar = 123 // toString converts to "123"

myVar = true // toString converts to "true"

myVar = false // toString converts to "false"

The table below shows the conversion of different values to Number, String, and Boolean:

Primitive value Convert to number Convert to string Converted to boolean Example
false 0 "false" false Try it »
true 1 "true" true Try it »
0 0 "0" false Try it »
1 1 "1" true Try it »
"0" 0 "0" true Try it »
"000" 0 "000" true Try it »
"1" 1 "1" true Try it »
NaN NaN "NaN" false Try it »
Infinity Infinity "Infinity" true Try it »
-Infinity -Infinity "-Infinity" true Try it »
"" 0 "" false Try it »
"20" 20 "20" true Try it »
"Runoob" NaN "Runoob" true Try it »
[ ] 0 "" true Try it »
[20] 20 "20" true Try it »
[10,20] NaN "10,20" true Try it »
["Runoob"] NaN "Runoob" true Try it »
["Runoob","Google"] NaN "Runoob,Google" true Try it »
function(){} NaN "function(){}" true Try it »
{ } NaN "[object Object]" true Try it »
null 0 "null" false Try it »
undefined NaN "undefined" false Try it »