Home > Article > Web Front-end > What Does the Double Tilde (~~) Operator Do in JavaScript?
Double Tilde Operator: A Deeper Dive into ~~
In JavaScript, you may encounter the ~~ operator, also known as the "double tilde" operator. While the single tilde ~ represents bitwise NOT, you may wonder what role the double tilde plays.
Contrary to intuition, ~~ does not perform a NOT of a NOT operation. Instead, it implicitly converts its operands to 32-bit integers and removes everything after the decimal point. This behavior applies to both numbers and strings.
Technically, ~~ behaves like the following function:
<code class="javascript">function(x) { if(x < 0) return Math.ceil(x); else return Math.floor(x); }</code>
However, it only provides accurate results when the operand x is within the range of -(2^31) to 2^31 - 1. Beyond this range, overflow occurs, leading to "wrapping around" of the number.
It may seem tempting to use ~~ for numeric parsing of string arguments, but this is discouraged. Overflow and incorrectness for non-integers make it a poor choice. Prefer x or Number(x) instead.
Understanding Double Tilde as NOT of NOT
To understand how ~~ effectively performs a NOT of a NOT operation, consider the following example:
The number -43.2 is represented as a signed 32-bit binary number:
-43.2 = 11111111111111111111111111010101 (2)
Applying bitwise NOT:
NOT -43.2 = 00000000000000000000000000101010 (2) = 42
A second application of bitwise NOT:
NOT 42 = 11111111111111111111111111010101 (2) = -43
Notice that the ~~ operator produces the same result as two consecutive bitwise NOT operations, even though it doesn't perform the NOT of a NOT operation in a straightforward manner.
The above is the detailed content of What Does the Double Tilde (~~) Operator Do in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!