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);
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)
.
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
It converts the value to an integer.