11

Possible Duplicate:
What is the “double tilde” (~~) operator in JavaScript?

I found this snip of code in a node.js library's source. What effect does ~~ have on the input variable?

inArray[3] = ~~input;

It's also used in other ways:

return ~~ ((a - b) / 864e5 / 7 + 1.5);
Community
  • 1
  • 1
Kato
  • 39,568
  • 6
  • 114
  • 140
  • 9
    Makes code confusing to read -_-. I hate how people are doing this recently; it makes me very angry. – Domenic Apr 10 '12 at 18:34
  • 1
    Heh, this is even more annoying than the double `!!`.. – Mike Christensen Apr 10 '12 at 18:37
  • @jasonbar can't search for ~~, but I did look :( For some reason "double tilde" never occurred to me! :) – Kato Apr 10 '12 at 18:39
  • @Kato: Just Google for a list of operators, then when you find a page of them, hit Ctrl-F (or Cmd-F), ~. :p – Elliot Bonneville Apr 10 '12 at 18:39
  • @ElliotBonneville I started on Google with operators in mind. Sometimes it's just easier to ask Humans. ;) – Kato Apr 10 '12 at 18:42
  • What library is that by the way? Curious as to the purpose of `return ~~ ((a - b) / 864e5 / 7 + 1.5);`. Probably a fast estimation of some sort but still – Alex Turpin Apr 10 '12 at 19:06
  • 1
    @Xeon06 [moment.js](https://github.com/timrwood/moment), the code is [here](https://github.com/timrwood/moment/blob/master/moment.js) on line 155 – Kato Apr 10 '12 at 20:25

3 Answers3

16

The ~ operator flips the bits of its operand. Using it twice flips the bits, then flips them again, returning a standard Javascript value equivalent to the operand, but in integer form. It's shorthand for parseInt(myInt).

Elliot Bonneville
  • 49,322
  • 23
  • 92
  • 122
10

It's a hackish way to truncate a value, a bit like what Math.floor does, except this behaves differently for negative numbers. For example, truncating -15.9 (~~-15.9) gives -15, but flooring it will always round towards the lowest number, so Math.floor(-15.9) will give 16.

Another way to do it is to OR with zero.

var a = 15.9 | 0; //a = 15
Community
  • 1
  • 1
Alex Turpin
  • 45,503
  • 23
  • 111
  • 144
2

It converts the value to an integer.

ThiefMaster
  • 298,938
  • 77
  • 579
  • 623