What the hell is "~~" in JavaScript?

2015-07-06 | #helper, #javascript

Some time ago I first stumbled upon this operator in a jQuery-plugin, which left me with a big questionmark. "~~" as in

var a = ~~b;

I know "!!" for being a doubled negation, which is essentially just a cast to boolean. Might this be something similiar? Yes it is. "~" is the bitwise negation of a value, so "~~" again is a doubled negation, flipping the ones and zeroes of a value back and forth.

This in itself is fairly unspectacular, weren't it for this implicit magic happening under the surface. The "~~"-operator effectively produces a real integer from almost every value, including NaN, null, undefined and such. Those non-values all result in a 0. Apart from that "~~" works like a Math.floor or Math.ceil, always moving in the direction of 0. So, some examples:

~~(2/0) = 0

~~Infinity = 0

~~(-2.9) = -2

~~3.4 = 3

All in all I don't know if i would recommend using this, since this is fairly obfuscated code with a lot of implicit functionality, but it's good to know nonetheless.