var str = '52'; var num = parseInt(str, 10); alert(typeof num + ' ' + num);
In the above chunk of code, you end up with “number 52” being chucked into the alert dialog. Yay. Now here is the slacker parsing version, which can be used instead of parseInt or parseFloat if you have a string containing a valid number.
var str = '52'; var num = +str; alert(typeof num + ' ' + num);
If you want to convert something to a boolean, you normally have to test it, as per the below example, which is a common way of mapping a bit to a Boolean using 0 for false, and 1 for true:
var num = 1; var bool = num === 1; alert(typeof bool + ' ' + bool);
So in the above example we end up with “boolean true”. But if we bear in mind the rules of truthy and falsey we can double-bang our way using the slacker parsing version.
var num = 1; var bool = !!num; alert(typeof bool + ' ' + bool);
The double bang (!!) basically means “NOT NOT”, which converts the value to a boolean and keeps it from being inverted.
A useful variation of this is rather obtuse but entirely fun BANG! BANG! WIGGLE!, which Robert pointed out to me. This can be used to coerce the result of an indexOf call into a boolean:
var value = 'test'; var containsE = !!~value.indexOf('e');