JavaScript Type Conversion
- Previous Page JS typeof
- Next Page JS Destructuring
Number()
Convert to number,String()
Convert to string,Boolean()
Convert to boolean value.
JavaScript Data Types
There are five data types that can contain values in JavaScript:
- String (string)
- Number (number)
- Boolean (boolean)
- Object (object)
- Function (function)
There are three types of objects:
- Object (Object)
- Date (Date)
- Array (Array)
There are two data types that cannot contain values:
- null
- undefined
typeof operator
You can use typeof
Operators to determine the data type of JavaScript variables.
Example
typeof "Bill" // Returns "string" typeof 3.14 // Returns "number" typeof NaN // Returns "number" typeof false // Returns "boolean" typeof [1,2,3,4] // Returns "object" typeof {name:'Bill', age:62} // Returns "object" typeof new Date() // Returns "object" typeof function () {} // Returns "function" typeof myCar // Returns "undefined" * typeof null // Returns "object"
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 an undefined variable is undefined
- The data type of an uninitialized variable is also undefined
You cannot use typeof
to determine whether a JavaScript object is an array (or date).
The data types of typeof
typeof
The operator is not a variable. It belongs to the operator. Operators (such as +
-
*
/
)There is no data type.
However,typeof
Always willReturns a stringIncluding the type of the operands).
Constructor property
constructor
The property returns the constructor function of all JavaScript variables.
Example
"Bill".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:'Bill', age:62}.constructor // Returns "function Object() { [native code] }" new Date().constructor // Returns "function Date() { [native code] }" function () {}.constructor // Returns "function Function(){ [native code] }"
You can check constructor
attribute to determine if an object is an array (including the word "Array"):
Example
function isArray(myArray) { return myArray.constructor.toString().indexOf("Array") > -1; }
Or even simpler, you can check if the object is an array function:
Example
function isArray(myArray) { return myArray.constructor === Array; }
You can check constructor
attribute to determine if an object is a date (including the word "Date"):
Example
function isDate(myDate) { return myDate.constructor.toString().indexOf("Date") > -1; }
Or even simpler, you can check if the object is a date function:
Example
function isDate(myDate) { return myDate.constructor === Date; }
JavaScript Type Conversion
JavaScript variables can be converted to new variables and another data type:
- By using JavaScript functions
- Through JavaScript itselfAutomaticallyConversion
Converts numbers to strings
Global method String()
Can convert numbers to strings.
It can be used with any type of number, text, variable, or expression:
Example
String(x) // Returns a string from the numeric variable x String(123) // Returns a string from the numeric text 123 String(100 + 23) // Returns a string from the number in the expression
Number methods toString()
Similarly.
Example
x.toString() (123).toString() (100 + 23).toString()
InNumber methodsIn this chapter, you will learn more methods that can be used to convert numbers to strings:
Method | Description |
---|---|
toExponential() | Returns a string that rounds the number and writes it using exponential notation. |
toFixed() | Returns a string that rounds the number and writes it using the specified number of decimal places. |
toPrecision() | Returns a string that represents the number with the specified length. |
Convert booleans to strings
Global method String()
Can convert booleans to strings.
String(false) // Returns "false" String(true) // Returns "true"
Boolean methods toString()
Similarly.
false.toString() // Returns "false" true.toString() // Returns "true"
Convert dates to strings
Global method String()
Can convert dates to strings.
String(Date())
Date methods toString()
Similarly.
Example
Date().toString()
InDate methodsIn this chapter, you can find more methods that can be used to convert dates to strings:
Method | Description |
---|---|
getDate() | Get a day counted as a number (1-31) |
getDay() | Or a week counted as a number (0-6) |
getFullYear() | Get a four-digit year (yyyy) |
getHours() | Get hour (0-23) |
getMilliseconds() | Get milliseconds (0-999) |
getMinutes() | Get minutes (0-59) |
getMonth() | Get month (0-11) |
getSeconds() | Get seconds (0-59) |
getTime() | Get time (milliseconds since January 1, 1970) |
Convert strings to numbers
Global method Number()
Can convert strings to numbers.
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, not a number).
Number("3.14") // Returns 3.14 Number(" ") // Returns 0 Number("") // Returns 0 Number("99 88") // Returns NaN
InNumber methodsIn this chapter, you will find more methods that can be used to convert strings to numbers:
Method | Description |
---|---|
parseFloat() | Parse the string and return a floating-point number. |
parseInt() | Parse the string and return an integer. |
Unary + operator
Unary +
OperatorsCan be used to convert variables to numbers:
Example
var y = "5"; // y is a string var x = + y; // x is a number
If the variable cannot be converted, it will still be a number, but the value will be NaN
(Not a number):
Example
var y = "Bill"; // y is a string var x = + y; // x is a number (NaN)
Convert booleans to numeric values
Global method Number()
Also, you can convert booleans to numbers.
Number(false) // Returns 0 Number(true) // Returns 1
Convert dates to numbers
Global method Number()
Can be used to convert dates to numbers.
d = new Date(); Number(d)
Date methods getTime()
Similarly.
d = new Date(); d.getTime()
Automatic type conversion
If JavaScript tries to operate on a "wrong" data type, it will try to convert the value to the "correct" type.
The results are 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" + 2 // Returns 52 Because 2 is converted to "2" "5" - 2 // Returns 3 Because "5" is converted to 5 "5" * "2" // Returns 10 Because "5" and "2" are converted to 5 and 2
automatic string conversion
JavaScript automatically calls the variable's toString()
Function, when you try to "output" an object or variable:
document.getElementById("demo").innerHTML = myVar; // If myVar = {name:"Fjohn"} // toString converts to "[object Object]" // If myVar = [1,2,3,4] // toString converts to "1,2,3,4" // If myVar = new Date() // toString converts to """"
Numbers and booleans are also converted, but not obviously:
// If myVar = 123 // toString converts to "123" // If myVar = true // toString converts to "true" // If myVar = false // toString converts to "false"
JavaScript Type Conversion Table
The following table lists the results of converting different JavaScript values to numbers, strings, and booleans:
Original Value | Convert to Number | Convert to String | Convert to Logical | Try It |
---|---|---|---|---|
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 |
"twenty" | NaN | "twenty" | true | Try It |
[ ] | 0 |
"" | true | Try It |
[20] | 20 |
"20" | true | Try It |
[10,20] | NaN | "10,20" | true | Try It |
["twenty"] | NaN | "twenty" | true | Try It |
["ten","twenty"] | NaN | "ten,twenty" | 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 |
Values in quotes indicate string values.
Red ValuesIndicates values that (some) programmers may not want.
- Previous Page JS typeof
- Next Page JS Destructuring