YouTip LogoYouTip

Js Type Conversion

JavaScript Type Conversion | Rookie Tutorial
Number() converts to a number, String() converts to a string, and 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 value:
  • null
  • undefined

The typeof Operator

You can use the typeof 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 is not declared) typeof null// returns object Try it yourself Β» 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 undeclared variable is undefined
If an object is a JavaScript Array or JavaScript Date, we cannot determine its 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() { } (3.14).constructor// returns function Number() { } false.constructor// returns function Boolean() { } [1,2,3,4].constructor// returns function Array() { } {name:'John', age:34}.constructor// returns function Object() { } new Date().constructor// returns function Date() { } function () {}.constructor // returns function Function(){ } Try it yourself Β» You can use the constructor property to check if an object is an array (contains the string "Array"):

Example

function isArray(myArray) { return myArray.constructor.toString().indexOf("Array") >-1; } Try it yourself Β» You can use the constructor property to check if an object is a date (contains the string "Date"):

Example

function isDate(myDate) { return myDate.constructor.toString().indexOf("Date") >-1; } Try it yourself Β»

JavaScript Type Conversion

JavaScript variables can be converted to a new variable or another data type:
  • By using JavaScript functions
  • Automatically by JavaScript itself

Converting Numbers to Strings

The global method String() can convert numbers to strings. This method can be used on any type of number, literal, variable, or expression:

Example

String(x)// converts variable x to a string and returns it String(123)// converts number 123 to a string and returns it String(100 + 23)// converts numeric expression to a string and returns it Try it yourself Β» The Number method toString() has the same effect.

Example

x.toString() (123).toString() (100 + 23).toString() Try it yourself Β» In the Number Methods section, you can find more methods for converting numbers to strings:
MethodDescription
toExponential()Converts a number to exponential notation.
toFixed()Converts a number to a string, keeping a specified number of decimals.
toPrecision()Formats a number to 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() has 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) The Date method toString() has the same effect.

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 functions for converting dates to strings:
MethodDescription
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. A string containing a number (e.g., "3.14") is converted to a number (e.g., 3.14). An empty string is converted to 0. Other strings are 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 Methods section, you can find more methods for converting strings to numbers:
MethodDescription
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 yourself Β» 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) Try it yourself Β»

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() has 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 it to a "correct" data type. The following outputs may not be what you expect: 5 + null// returns 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 automatically calls the variable's toString() method: document.getElementById("demo").innerHTML = myVar; myVar = {name:"Fjohn"} // toString converts to "" 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 frequently converted: myVar = 123 // toString converts to "123" myVar = true // toString converts to "true" myVar = false // toString converts to "false" The table below shows how different values are converted to Number, String, and Boolean:
Original ValueConverted to NumberConverted to StringConverted to BooleanExample
false0"false"falseTry it yourself Β»
true1"true"trueTry it yourself Β»
00"0"falseTry it yourself Β»
← Event Key KeyJs Typeof β†’