Web Development

JavaScript Type Conversion

JavaScript Type Conversion is section 19 of Beginner’s Guide to JavaScript.

First of all let’s summarize all of the data types supported by JS. In JavaScript there are 5 different data types that can contain values:

  • string
  • number
  • boolean
  • object
  • function

There are 3 types of objects:

  • Object
  • Date
  • Array

And 2 data types that cannot contain values:

  • null
  • undefined

You can use the typeof operator to find the data type of a JavaScript variable. If you check the type of following variables, you can observe following.

  • 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

The constructor property returns the constructor function for all JavaScript variables.

“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 check the constructor property to find out if an object is a specific type.

[code languague=”js”] function isArray(myArray) {
return myArray.constructor.toString().indexOf(“Array”) > -1;
}
[/code]

JavaScript Type Conversion

JavaScript variables can be converted to a new variable and another data type:

  • By the use of a JavaScript functions
  • Automatically by JavaScript itself

Converting Other Data Types to a String

Converting Numbers to Strings

The global method String() can convert numbers to strings. It can be used on any type of numbers, literals, variables, or expressions.

String(x)         // returns a string from a number variable x
String(123)       // returns a string from a number literal 123
String(100 + 23// returns a string from a number from an expression

The Number method toString() does the same. But there are more methods on Number which returns a string.

x.toString()
(123).toString()
(100 + 23).toString()

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() 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 date in string format

The Date method toString() does the same. But there are more methods on Date which returns a string.

Date().toString()   //  returns date in string format

Converting Other Data Types to a Number

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

Also parsing methods in Number can be used to convert Strings into Number with integers or floating points.

Converting Booleans to Numbers

The global method Number() can also convert booleans to numbers.

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

Converting Dates to Numbers

The global method Number() can be used to convert dates to numbers.

d = new Date();
Number(d)          // returns the miliseconds

The date method getTime() does the same.

d = new Date();
d.getTime()        // returns the miliseconds

Automatic Conversions

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. For example look at the following.

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

JavaScript automatically calls the variable’s toString() function when you try to “output” an object or a variable. Numbers and booleans are also converted, but this is not very visible. For example look at the following situations.

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”

myVar = 123             // toString converts to “123”
myVar = true            // toString converts to “true”
myVar = false           // toString converts to “false”


What’s Next?

Learn what is Throw Try Catch

 

 

Join Our Newsletter Today

Stay updated with all latest updates.
Give it a try, you can unsubscribe anytime.
Subscribe
SUBSCRIBE NOW

About the author

Sandeep Likhar

Sandeep Likhar from Indore India, Blogger, eBook Designer and Founder of LetsDnD. Having five years of experience in industry as a Digital Publishing Expert and eBook Converter providing services to Authors, Publishers and distributors worldwide. Proficient in converting books into various formats HTML, epub, mobi, word, PDF including all major online platforms iTunes, Kobo, Kindle, Createspace, B&N, Smashwords and more.

Leave a Reply

Be the First to Comment!

Notify of
avatar
wpDiscuz
DON’T MISS OUT!
Subscribe To Newsletter
Be the first to get latest updates and exclusive content straight to your email inbox.
Stay Updated
Give it a try, you can unsubscribe anytime.

Join Our Newsletter Today

Stay updated with all latest updates.
Give it a try, you can unsubscribe anytime.
Subscribe
SUBSCRIBE NOW