X

JavaScript conversion tips

conversion

In this post I will write about some tips on JavaScript Conversion from type to values etc.

Tip 1: Boolean values
In JavaScript one can use the double not (!!) to convert a variable to a Boolean. What the !! operator (poor man casting) does is, it first cast the data to a true Boolean and then it flips it, and the second operator flips it back to the correct Boolean value.

var myBool = !!"false";  // true

var testNull = !!null; // false

myBool = !!1; //true

myBool = !!0; //false

myBool = !!""; //false

myBool = !!window.helloWorld; //false

//another example to clarify
var x = "abcd"
var isNotEmpty = !!x.length;
x.length   // 4
!x.length  // false
!!x.length // true

Tip 2: Convert to Number
In JavaScript one can use the + to convert a string to a number. I mean the plus can be obscure, one can also >> shift operator and also use parseInt but remember parseInt may give you different results than + like the example below. Also here is some jsperf on int casting.

var myNumber = +"123456"; //now 123456

//there is also parseInt
var pi = parseInt("3.14") // returns 3 by default it uses the 10 radix same as parseInt("3.14, 10);

var pi_dec = +"3.14" // returns 3.14

var str = '100';

var str_int = str >> 0; // now str_int is 100

var result = Number("12345"); //rather slow

var bitwise = ~~'123'; //fastest way to convert

Tip 3: Convert to String
This is the inverse of the + you saw above, you can covert a value into a string by concat with empty string “”. If you wish to know which one is the fastest way to cast as string one can check out this jsperf

var myStr = 123 + ""; //becomes a string "123"

var myStr2 = String(null); //becomes "null"
var myStr3 = null + ""; //becomes "null" also
null.toString(); //throws an error
Taswar Bhatti:
Related Post