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.

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.

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

Taswar Bhatti Avatar

Written by