I see a lot of confusion among the javascript developers when it comes to casting in javascript.
Casting To A Number
let's say you have a String and you want to convert it to a Number. one would say I will use parseInt() or parseFloat().
but there is even an easier way of doing it. no need to be worried if it is an Integer or Float.
Yeah, it's possible to cast to a number by using the unary plus operator
+'20' === 20; // returns true var str = "20"; var num = +str; // returns 20 str = "20.3"; num = +str // returns 20.3
Casting To A String
to cast a number to a string there is a tricky way of doing it.
'' + 60 === '60'; // returns true var myInt = 60; var myStr = myInt + ''; // returns "60"
Casting To A Boolean
you can cast to boolean by using the not operator twice !!.
I see mostly people using this in their return statements. instead of doing if else. they use !!.
!!null === !!NaN === !!undefined === !!'' === !!0 === false !!"Any String" === !!"2" === !!"0" === true
I hope you found this tutorial useful.
Daniel
Jan 12, 2012 @ 07:09:03
Hi…
http://www.webcamgirls4.com/…