Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does ~~ do in JavaScript/node.js? [duplicate]

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);
like image 778
Kato Avatar asked Apr 10 '12 18:04

Kato


3 Answers

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).

like image 52
Elliot Bonneville Avatar answered Oct 11 '22 08:10

Elliot Bonneville


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
like image 27
Alex Turpin Avatar answered Oct 11 '22 08:10

Alex Turpin


It converts the value to an integer.

like image 34
ThiefMaster Avatar answered Oct 11 '22 09:10

ThiefMaster