Simple type casting in Javascript

This is my first blog for my very favorite language.

JavaScript is a very flexible language that would make to do many magical things. But the programming this language should be done careful since every browser is running in a single thread.

Type casting in JavaScript

Number

We all know the string or date can be converted to number using parseInt/parseFloat. But we can also use the “+” operator to do the same.

var d = +"43" //43

var d = +"4.3" //4.3

var d = +"4e" //NaN

var d = +new Date() //returns date value in milliseconds.

String

ToString method can be used to convert any number, boolean or date to string value. But it can be more simple by using the concatenating a “” at the end.

var d = 4 + "" //"4"

var d = new Date() + "" //"Wed Jul 22 2015 15:40:26 GMT+0530 (India Standard Time)"

String to Boolean

There is no simple way to cast from “true” string value to true boolean type. We have to do as follows.

var d = val == "true" ? true : val == "false" : false;

Advertisements