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:
- string
- number
- boolean
- object
- function
- symbol
3 object types:
- Object
- Date
- Array
2 data types that contain no values:
- null
- undefined
The typeof Operator
You can use the typeof operator to find 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 is not declared)
typeof null // Returns "object"
Please note:
- The data type of NaN is number
- The data type of an array is object
- The data type of a date is object
- The data type of null is object
- The data type of an undefined variable is undefined
If the object is a JavaScript Array or a JavaScript Date, we cannot determine their type using typeof because both return "object".
The constructor Property
The constructor property returns the constructor function for all JavaScript variables.
Example
"John".constructor // Returns function String() { [native code] }
(3.14).constructor // Returns function Number() { [native code] }
false.constructor // Returns function Boolean() { [native code] }
[1,2,3,4].constructor // Returns function Array() { [native code] }
{name:'John', age:34}.constructor // Returns function Object() { [native code] }
new Date().constructor // Returns function Date() { [native code] }
function () {}.constructor // Returns function Function(){ [native code] }
You can use the constructor property to check if an object is an array (contains the word "Array"):
Example
function isArray(myArray) {
return myArray.constructor.toString().indexOf("Array") > -1;
}
You can use the constructor property to check if an object is a date (contains the word "Date"):
Example
function isDate(myDate) {
return myDate.constructor.toString().indexOf("Date") > -1;
}
JavaScript Type Conversion
JavaScript variables can be converted to a new variable or another data type:
- By using a JavaScript function
- By JavaScript itself automatically
Converting Numbers to Strings
The global method String() can convert numbers to strings.
This method can be used on any type of numbers, literals, variables, or expressions:
Example
String(x) // Returns the string representation of the variable x
String(123) // Returns "123"
String(100 + 23) // Returns "123"
The Number method toString() does the same.
Example
x.toString()
(123).toString()
(100 + 23).toString()
In the Number Methods section, you can find more methods that can be used to convert numbers to strings:
Method | Description |
---|---|
toExponential() | Returns a string, with a number rounded and written using exponential notation. |
toFixed() | Returns a string, with the number written with a specified number of decimals. |
toPrecision() | Returns a string, with a number written with a specified length. |
Converting Booleans to Strings
The global method String() can convert booleans to strings.
String(false) // Returns "false"
String(true) // Returns "true"
The Boolean method toString() also does the same.
false.toString() // Returns "false"
true.toString() // Returns "true"
Converting Dates to Strings
The Date() method returns a string.
Date() // Returns Thu Jul 17 2014 15:38:19 GMT+0200 (W. Europe Daylight Time)
The global method String() can convert dates to strings.
String(new Date()) // Returns Thu Jul 17 2014 15:38:19 GMT+0200 (W. Europe Daylight Time)
The Date method toString() also does the same.
Example
obj = new Date()
obj.toString() // Returns Thu Jul 17 2014 15:38:19 GMT+0200 (W. Europe Daylight Time)
In the Date Methods section, you can find more methods that can be used to convert 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 (4 digits) from a Date object. |
getHours() | Returns the hour (0-23) from a Date object. |
getMilliseconds() | Returns the milliseconds (0-999) from a Date object. |
getMinutes() | Returns the minutes (0-59) from a Date object. |
getMonth() | Returns the month (0-11) from a Date object. |
getSeconds() | Returns the seconds (0-59) from a Date object. |
getTime() | Returns the number of milliseconds since January 1, 1970. |
Converting Strings to Numbers
The global method Number() can convert strings to numbers.
Strings containing numbers (like "3.14") convert to numbers (like 3.14).
Empty strings convert to 0.
Anything else converts 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 Methods section, you can find more methods that can be used to convert 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
If the variable cannot be converted, it will still become 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)
Converting Booleans to Numbers
The global method Number() can convert booleans to numbers.
Number(false) // Returns 0
Number(true) // Returns 1
Converting Dates to Numbers
The global method Number() can convert dates to numbers.
d = new Date();
Number(d) // Returns 1404568027739
The Date method getTime() also does the same.
d = new Date();
d.getTime() // Returns 1404568027739
Automatic Type Conversion
When JavaScript tries to operate on a "wrong" data type, it will try to convert the value to a "right" type.
The result is not always what you expect:
5 + null // Returns 5 because null is converted to 0
"5" + null // Returns "5null" because null is converted to "null"
"5" + 1 // Returns "51" because 1 is converted to "1"
"5" - 1 // Returns 4 because "5" is converted to 5
Automatic String Conversion
JavaScript automatically calls the variable's toString() method when you try to "output" an object or a variable:
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 strings:
myVar = 123 // toString converts to "123"
myVar = true // toString converts to "true"
myVar = false // toString converts to "false"
The following table shows the conversion of different values to Number, String, and Boolean:
Original Value | Converted to Number | Converted 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 » |
"tutorialpro" | NaN | "tutorialpro" | true | Try it » |
[ ] | 0 | "" | true | Try it » |
[20] | 20 | "20" | true | Try it » |
[10,20] | NaN | "10,20" | true | Try it » |
["tutorialpro"] | NaN | "tutorialpro" | true | Try it » |
["tutorialpro","Google"] | NaN | "tutorialpro,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 » |