Skip to main content

What is the "double tilde' (~~) operator in JavaScript?


I'm seeing this in some code, and I have no idea what it does:




var jdn = function(y, m, d) {
var tmp = (month <= 2 ? -1 : 0);
return ~~((1461 * (y + 4800 + tmp)) / 4) +
~~((367 * (m - 2 - 12 * tmp)) / 12) -
~~((3 * ((year + 4900 + tmp) / 100)) / 4) +
d - 2483620;
};



What's the ~~ operator do?


Source: Tips4allCCNA FINAL EXAM

Comments

  1. That ~~ is a double NOT bitwise operator.

    It is used as a faster substitute for Math.floor().

    ReplyDelete
  2. It hides the intention of the code.

    It's two single tilde operators, so it does a bitwise complement (bitwise not) twice. The operations take out each other, so the only remaining effect is the conversion that is done before the first operator is applied, i.e. converting the value to an integer number.

    Some use it as a faster alternative to Math.floor, but the speed difference is not that dramatic, and in most cases it's just micro optimisation. Unless you have a piece of code that really needs to be optimised, you should use code that descibes what it does instead of code that uses a side effect of a non-operation.

    Update 2011-08:

    With optimisation of the Javscript engine in browsers, the performance for operators and functions change. With current browsers, using ~~ instead of Math.floor is somewhat faster in some browswers, and not faster at all in some browsers. If you really need that extra bit of performance, you would need to write different optimised code for each browsers.

    http://jsperf.com/tilde-vs-floor

    ReplyDelete

Post a Comment

Popular posts from this blog

Wildcards in a hosts file

I want to setup my local development machine so that any requests for *.local are redirected to localhost . The idea is that as I develop multiple sites, I can just add vhosts to Apache called site1.local , site2.local etc, and have them all resolve to localhost , while Apache serves a different site accordingly.