JavaScript Type Conversions


Number() is converted to a number, String() is converted to a string, and Boolean() is converted to a Boolean value.


JavaScript Data Types

There are 6 different data types in JavaScript:

  • string

  • number

  • boolean

  • object

  • function

  • symbol

3 object types:

  • Object

  • Date

  • Array

2 data types that do not contain any values:

  • null

  • undefined


typeof Operator

You can use the typeof operator to view the data types of JavaScript variables.

Example

typeof "Jake" // return string
typeof 3.14 // return number
typeof NaN // return number
typeof false // return boolean
typeof [1,2,3,4] // return object
typeof {name:'John', age:34} // return object
typeof new Date() // return object
typeof function () {} // return function
typeof myCar // return undefined (if myCar is not declared)
typeof null // return object

Try It! 

Please note:

  • The data type of NaN is number

  • The data type of Array is object

  • The data type of Date is object

  • The data type of null is object

  • The data type of undefined variables is undefined

If the object is JavaScript Array or JavaScript Date, we can't judge their type by typeof , because they all return object.


constructor Property

The constructor property returns the constructors of all JavaScript variables.

Example

"John".constructor // return function String() {[native code]}
(3.14).constructor // Return function Number() {[native code]}
false.constructor // return function Boolean() {[native code]}
[1,2,3,4].constructor // Return function Array() {[native code]}
{name:'John', age:34}.constructor // Return function Object() {[native code]}
new Date().constructor // Return function Date() {[native code]}
function () {}.constructor // Return function Function(){ [native code]}

Try It! 

You can use the constructor property to check whether the object is an array (including 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 the object is a date (including the string "Date"):

Example

function isDate(myDate) {
     return myDate.constructor.toString().indexOf("Date")> -1;
}

 Try It! 


JavaScript type conversions

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

  • By using JavaScript functions

  • Automatic conversion via JavaScript itself


Convert number to string

The global method String() can convert numbers to strings.

This method can be used for any type of numbers, letters, variables, expressions:

Example

String(x) // Convert the variable x to a string and return
String(123) // Convert the number 123 to a string and return
String(100 + 23) // Convert the numeric expression to a string and return

Try It! 

The Number method toString() has the same effect.

Example

x.toString()
(123).toString()
(100 + 23).toString()

Try It! 

In the Number Object chapter, you can find more ways to convert numbers to strings:

MethodDescription
toExponential()Convert the value of the object to exponential notation.
toFixed()Convert the number to a string, the result has a number of specified digits after the decimal point.
toPrecision()Format the number to the specified length.



Convert boolean Value to string

The global method String() can convert Boolean values to strings.

String(false)        // returns "false"
String(true)         // returns "true"

The Boolean method toString() also has the same effect.

false.toString()     // returns "false"
true.toString()      // returns "true"



Convert date to string

Date() returns a string.

Date()      // result: Sat Aug 17 2019 15:38:19 GMT+0200 (W. Europe Daylight Time)

The global method String() can convert a date object into a string.

String(new Date())      // result: Sat Aug 17 2019 15:38:19 GMT+0200 (W. Europe Daylight Time)

The Date method toString() has the same effect.

Example

obj = new Date()
obj.toString()   // result: Sat Aug 17 2019 15:38:19 GMT+0200 (W. Europe Daylight Time)

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

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



Convert string to number

The global method Number() can convert a string to a number.

Strings containing numbers (such as "3.14") are converted to numbers (such as 3.14).

An empty string is converted to 0.

Other strings will be converted to NaN (not a number).

Number( "3.14" )    // returns 3.14
Number( "" )       // returns 0
Number( "" )        // returns 0
Number( "99 88" )   // returns NaN

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

MethodDescription
parseFloat()Parse a string and return a floating point number.
parseInt()Parse a string and return an integer.



Unary Operator +

Operator + can be used to convert variables to numbers:

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 the value is NaN (not a number):

Example

var y = "John"; // y is a string
var x = + y; // x is a number (NaN)

Try It! 


Convert Boolean Value to Number

The global method Number() can convert Boolean values to numbers.

Number( false) // returns 0

Number( true) // returns 1


Convert Date to Number

The global method Number() can convert the date into a number.

d = new Date();

Number(d) // returns 1404568027739

The date method getTime() also has the same effect.

d = new Date();

d.getTime() // returns 1404568027739


Automatic Conversion Type

When JavaScript tries to manipulate a "wrong" data type, it will automatically be converted to the "correct" data type.

The following output is not what you expected:

5 + null // return 5, null converted to 0

"5" + null // return "5null", null converted to "null"

"5" + 1 // returns "51", 1 is converted to "1"

"5"-1 // returns 4, "5" is converted to 5


Automatic Conversion to String

When you try to output an object or a variable, JavaScript will automatically call the toString() method of the variable:

document.getElementById("demo").innerHTML = myVar;


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

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

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

Numbers and Boolean values are often converted to each other:

myVar = 123 // toString is converted to "123"

myVar = true // toString is converted to "true"

myVar = false // toString is converted to "false"

The following table shows the use of different values to convert to numbers (Number), character strings (String), and boolean values (Boolean):

Original ValueConvert to NumberConvert to StringConvert to BooleanExample
false0"false"false Try It! 
true1"true"true Try It! 
00"0"false Try It! 
11"1"true Try It! 
"0"0"0"true Try It! 
"000"0"000"true Try It! 
"1"1"1"true Try It! 
NaNNaN"NaN"false Try It! 
InfinityInfinity"Infinity"true Try It! 
-Infinity-Infinity"-Infinity"true Try It! 
""0""false Try It! 
"20"20"20"true Try It! 
"TutorialFish"NaN"TutorialFish"true Try It! 
[ ]0""true Try It! 
[20]20"20"true Try It! 
[10,20]NaN"10,20"true Try It! 
["TutorialFish"]NaN"TutorialFish"true Try It! 
["TutorialFish","Google"]NaN"TutorialFish,Google"true Try It! 
function(){}NaN"function(){}"true Try It! 
{ }NaN"[object Object]"true Try It! 
null0"null"false Try It! 
undefinedNaN"undefined"false Try It!