WEB DEVELOPER SITE
HTMLCSSJAVASCRIPTSQLPHPBOOTSTRAPJQUERYANGULARXML
 

JavaScript Type Conversion


JavaScript typeof, null, undefined, valueOf ().


JavaScript Data Types

There are 5 different data types in JavaScript:

  • string
  • number
  • boolean
  • object
  • function

3 types of objects:

  • Object
  • Date
  • Array

2 data types without any values:

  • null
  • undefined

The typeof Operator

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

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 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

If the object is a JavaScript Array or JavaScript Date, we can't determine their type by typeof , because both return object.

Example

"John" .constructor // Return function String () {[native code]} (3.14) .constructor // returns 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 // returns function Object () {[native code]} new Date (). constructor // returns function Date () {[native code]} function () {} .constructor // return function Function () {[native code]}
Try it Yourself »

You can use the constructor property to see if the object is an array (containing the string "Array"):/p>

Example

function isArray(myArray) { return myArray.constructor.toString().indexOf("Array") > -1; }
Try it Yourself »

You can use the constructor property to see if the object is a date (including 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 new variables or other data types:
  • By using JavaScript functions
  • Automatic conversion via JavaScript

    Converting Numbers to Strings

    Global method String () converts a number to a string.

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

    Example

    String (x) // converts the variable x to a string and returns String (123) // convert the number 123 to a string and return String (100 + 23) // convert numeric expression to string and return
    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 ways to convert numbers to strings:

    Method Description
    toExponential () Converts the value of the object to exponential notation.
    toFixed () Converts a number to a string. The result has a specified number of digits after the decimal point.
    toPrecision () Format the number to the specified length.

    Converting Booleans to Strings

    The global method String () converts a Boolean value to a string.

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

    The Boolean method toString() does the same.

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

    Converting Dates to Strings

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

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

    The Date method toString() does the same.

    Example

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

    In the chapter Date Methods, you will find more methods that can be used to convert dates to strings:

    Method Description
    getDate() Get the day as a number (1-31)
    getDay() Get the weekday a number (0-6)
    getFullYear() Get the four digit year (yyyy)
    getHours() Get the hour (0-23)
    getMilliseconds() Get the milliseconds (0-999)
    getMinutes() Get the minutes (0-59)
    getMonth() Get the month (0-11)
    getSeconds() Get the seconds (0-59)
    getTime() Get the time (milliseconds since January 1, 1970)

    Converting Strings to Numbers

    Global method Number () converts a string to a number.

    String contains numbers (e.g. "3.14") converted to numbers (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

    Operator + can be used to convert variables 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

    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 Yourself »

    If the variable cannot be converted, it will still be a number, but the value will be 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 () converts a Boolean value to a number.

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

    Converting Dates to Numbers

    The global method Number () converts a date to a number.

    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 attempts to manipulate a "wrong" data type, it will automatically convert to a "correct" data type. The following output is not what you expected:
    5 + null // returns 5 null converted to 0 "5" + null // returns "5null" null converted to "null" "5" + 1 // returns "51" 1 converted to "1" "5"-1 // returns 4 "5" converted to 5
    Try it Yourself »

    Automatic String Conversion

    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 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"

    JavaScript Type Conversion Table

    The following table shows the conversion of numbers to numbers, strings, and booleans using different values:

    Original
    Value
    Converted
    to Number
    Converted
    to String
    Converted
    to Boolean
    Try it
    false 0 "false" false
    true 1 "true" true
    0 0 "0" false
    1 1 "1" true
    "0" 0 "0" true
    "1" 1 "1" true
    NaN NaN "NaN" false
    Infinity Infinity "Infinity" true
    -Infinity -Infinity "- Infinity" true
    "" 0 "" false
    "20" 20 "20" true
    "twenty" NaN "twenty" true
    [ ] 0 "" true
    [20] 20 "20" true
    [10,20] NaN "10,20" true
    ["twenty"] NaN "twenty" true
    ["ten","twenty"] NaN "ten,twenty" true
    function(){} NaN "function(){}" true
    { } NaN "[object Object]" true
    null 0 "null" false
    undefined NaN "undefined" false

    Values in statements demonstrate string values.

    Red values demonstrate values (a few) software engineers may not expect.