From the spec, Bitwise NOT, ~
- Let
expr
be the result of evaluating UnaryExpression.- Let
oldValue
beToInt32(GetValue(expr))
.- Return the result of applying bitwise complement to
oldValue
. The result is a signed 32-bit integer.
Definition of ToInt32
here.
The "complement" of a 32-bit integer i
is i XOR 0xFFFFFFFF
.
So put this all together and you have ~~i
as meaning
ToInt32(i) XOR 0xFFFFFFFF XOR 0xFFFFFFFF
// same as
ToInt32(i) XOR 0x00000000
// same as
ToInt32(i)
Keep in mind the differences in rounding direction for negative numbers.
Personally I prefer using x | 0
over ~~x
because it involves fewer operations for the same result.