in javascript hack ~ read.

Javascript Hack: The Double Tilde ~~

So recently I've been trying to sharpen up my javascript skills. One of the sites I've been using a bit is codewars.com (because studying is always a bit easier if you can do it competatively). Whilst going through some competitors answers to a particular challenge, I noticed the double tilde (~~) in javascript. I'm usually pretty good about these things, but this forced me to google.

Potential Usage

Essentially, this is used to remove a decimal place from a number. It does not round, it simply removes the decimal place. This can be handy if you want a quick (though not very readable way) to constrain numbers, especially if you are doing floating point arithmetic and find that suprisingly:
» 2.01 + 0.98 #=> 2.9899999999999998

WHAT?!?!

This is because javascript stores floats as binary numbers and sometimes the binary bits just don't line up. (I'm aware there is a much more specific answer and I'll probably cover this in some other post).

Enter the tilde
So this little trick can be great if you are working with floating point math and want a quick way to remove those pesky rounding errors that happen when working with decimals in javascript.

How It Works

So, if you are not familiar with bitwise operators (and honestly I am not at the moment) you should know that the tilde returns the bitwise complement for the current number. Translation: Since numbers are stored in binary, it turns all the ones to zeros and all of the zeros to ones.__

For Example:

If you have −43.21 it becomes 111111111111111111111111110101012
The if you do ~ −43.21 it becomes 000000000000000000000000001010102

Doing a double tilde essentially drops rounds the number toward zero. Which means that positive floats will lose the decimal portion. However, in our example −43.21 would become −42.

For me, this is the main reason I will leave this trick as just a trick.

Caveat Emptor

Pros
1) So according to JsPerf it is slightly faster. Though honestly if 0.59% speedups matter for your floating point conversions, you might be doing something wrong.
2) It is also faster to type
Again, if you are optimizing for key strokes, this might be a problem, unless you are playing code golf.
3) It will impress your friends and neighbors.
Seriously. Once they've had to google this article like you did, they too will be massively impressed at your knowlege of obscure bit-shifting tactics

Cons
1) It's hard to read. Math.floor() is longer to type, but it makes sense to even the novice programmer.
2) It doesn't play well with negative numbers. I suppose you could always work around this, but this seems like the biggest negative to me.

Conclusion (TL;DR)

Use it with care. I probably wouldn't use this in production code. But for something quick or in a competition to show off my javascript-hackery (á la code wars) I will probably pick up this trick again.

comments powered by Disqus