JavaScript type conversion



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


JavaScript Data Types

There are 5 different data types in JavaScript:

  • string

  • number

  • boolean

  • ##object

  • function

3 object types:

  • Object

  • Date

  • Array

2 data types that contain no value:

  • null

  • undefined


typeof operator

You can use the

typeof operator to view the data type of a JavaScript variable.

Instance

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>php.cn</title>
</head>
<body>

<p> typeof 操作符返回变量、对象、函数、表达式的类型。</p>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = 
    typeof "john" + "<br>" +
    typeof 3.14 + "<br>" +
    typeof NaN + "<br>" +
    typeof false + "<br>" +
    typeof [1,2,3,4] + "<br>" +
    typeof {name:'john', age:34} + "<br>" +
    typeof new Date() + "<br>" +
    typeof function () {} + "<br>" +
    typeof myCar + "<br>" +
    typeof null;
</script>

</body>
</html>

Run instance»Click the "Run instance" button to view the online instance

Please note:

  • The data type of NaN is number

  • The data type of array (Array) is object

  • The data type of date (Date) is object

  • The data type of null is object

  • It is an undefined variable The data type is undefined

If the object is JavaScript Array or JavaScript Date, we cannot judge their type through

typeof, because they all return Object.


constructor property

constructor property returns the constructor function for all JavaScript variables.

Instance

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>php.cn</title>
</head>
<body>

<p> constructor 属性返回变量或对象的构造函数。</p>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = 
    "john".constructor + "<br>" +
    (3.14).constructor + "<br>" +
    false.constructor + "<br>" +
    [1,2,3,4].constructor + "<br>" +
    {name:'john', age:34}.constructor + "<br>" +
    new Date().constructor + "<br>" +
    function () {}.constructor;
</script>

</body>
</html>

Run instance»Click the "Run instance" button to view the online instance

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

Instance

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>php.cn</title>
</head>
<body>

<p>判断是否为数组。</p>
<p id="demo"></p>
<script>
var fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo").innerHTML = isArray(fruits);
function isArray(myArray) {
    return myArray.constructor.toString().indexOf("Array") > -1;
}
</script>

</body>
</html>

Run Instance»Click the "Run Instance" button View online examples

You can use the constructor property to see if the object is a date (Contains the string "Date"):

Instance

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>php.cn</title>
</head>
<body>

<p>判断是否为日期。</p>
<p id="demo"></p>
<script>
var myDate = new Date();
document.getElementById("demo").innerHTML = isDate(myDate);
function isDate(myDate) {
    return myDate.constructor.toString().indexOf("Date") > -1;
}
</script>

</body>
</html>

Run Instance»Click the "Run Instance" button View online examples


JavaScript Type Conversion

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

  • By using JavaScript functions

  • Automatic conversion through JavaScript itself


Convert numbers to strings

Global methodString() You can Convert numbers to strings.

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

Example

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>php.cn</title>
</head>
<body>

<p> String() 方法可以将数字转换为字符串。</p>
<p id="demo"></p>
<script>
var x = 123;
document.getElementById("demo").innerHTML =
    String(x) + "<br>" +
    String(123) + "<br>" +
    String(100 + 23);
</script>
</body>
</html>

Running example »

Click the "Run Instance" button to view the online instance

Number method toString() also has the same effect.

Instance

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>php.cn</title>
</head>
<body>

<p>toString() 方法将数字转换为字符串。</p>
<p id="demo"></p>
<script>
var x = 123;
document.getElementById("demo").innerHTML =
    x.toString() + "<br>" +
   (123).toString() + "<br>" +
   (100 + 23).toString();
</script>

</body>
</html>

Run instance»

Click the "Run instance" button to view the online instance

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

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

Convert Boolean value to string

Global method String() You can convert Boolean value to string.

String(false)                                                                                                                            "true"
Boolean methodtoString() also has the same effect.
false.toString()

// Return "false"true.toString()

// Return "true"

Convert date to string

Global method
String()

You can convert date to string.

String(Date())

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

Date method
toString( ) also has the same effect.
Example

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

In the Date method chapter, You can view more functions for converting dates to strings:
Method

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



Convert a string to a number

Global method Number() You can convert a string to a number.

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

Empty strings are converted to 0.

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

Number("3.14") // Return 3.14
Number(" ") // Return 0
Number("")                                                                                     Returns NaN
In the Number method chapter, you can see more methods for converting strings to numbers:
Method

Description
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 a variable into a number:

Example

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>php.cn</title>
</head>
<body>

<p> typeof 操作符返回变量或表达式的类型。</p>
<button onclick="myFunction()">点我</button>
<p id="demo"></p>
<script>
function myFunction() {
    var y = "5";
    var x = + y;
    document.getElementById("demo").innerHTML =
		typeof y + "<br>" + typeof x;
}
</script>

</body>
</html>

Run Example»

Click the "Run Example" button to view the online example

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

Instance

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>php.cn</title>
</head>
<body>

<p> typeof 操作符返回变量或表达式的类型。</p>
<button onclick="myFunction()">点我</button>
<p id="demo"></p>
<script>
function myFunction() {
    var y = "John";
    var x = + y;
    document.getElementById("demo").innerHTML =
		typeof x + "<br>" + x;
}
</script>

</body>
</html>

Run Instance»

Click the "Run Instance" button to view the online instance


Convert Boolean value to number

Global methodNumber() Convert Boolean value to number.

Number(false) // Return 0
Number(true) // Return 1



Convert date to number

Global methodNumber() Convert date to number.

d = new Date();
Number(d) // Return 1404568027739

Date method getTime() also has the same effect.

d = new Date();
d.getTime() // Return 1404568027739



Automatic conversion of types

When JavaScript attempts to operate on a "wrong" data type, it will automatically convert to the "correct" data type.

The following output result is not what you expect:

5 + null // Return 5 null is converted to 0
"5" + null // Returns "5null" null is 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;

// if myVar = {name:"Fjohn"} // toString conversion For "[object Object]"
// if myVar = [1,2,3,4] // toString is converted to "1,2,3,4"
// if myVar = new Date() // toString is converted to "Fri Jul 18 2014 09:08:55 GMT+0200"

Numbers and Boolean values They are also often converted to each other:

// if myVar = 123 // toString is converted to "123"
// if myVar = true // toString is converted For "true"
// if myVar = false                                                                                                                                     // toString is converted to "false"