The double tilde (
While the single tilde (
~) performs a bitwise NOT operation, the double tilde performs two bitwise NOT operations consecutively.
Essentially, this double operation results in throwing anything after a decimal point and creating an integer.
Here's an example:
const num = 5.7; const int = ~~num; console.log(int); // 👉 Output: 5
Here, we used the double tilde operator to round down the number 5.7 to 5.
~~ Operator vs. Math.floor()
The double tilde (
~~) operator can be a faster alternative to
Math.floor() for rounding down numbers.
However, there are some critical behavioral differences between the two, especially when dealing with negative numbers.
For positive numbers, both the
~~ operator and
Math.floor() yield the same results. However, for negative numbers, the
~~ operator removes the decimal part, whereas
Math.floor() rounds the number down to the nearest integer.
Let's look at an example comparing the two methods:
const positiveNum = 5.7; const negativeNum = -5.7; console.log(~~positiveNum); // 👉 Output: 5 console.log(Math.floor(positiveNum)); // 👉 Output: 5 console.log(~~negativeNum); // 👉 Output: -5 console.log(Math.floor(negativeNum)); // 👉 Output: -6
While the double tilde operator is faster and takes less space, using
Math.floor() improves readability, making it easier for others to understand the code's intention. And it would help if you always aimed to write readable code.
Ultimately, the choice between the two depends on the specific use case and the trade-offs between performance and readability.
Other Uses of the Double Tilde ~~ Operator
Beyond rounding down numbers, the double tilde (
It can be used for converting strings to numbers, as it removes any non-numeric characters in the process. This makes it a handy alternative to
parseInt() for simple number conversion tasks.
The double tilde operator is similar to the
Math.trunc() function, as both remove the decimal part of a number. However, remember that they are not the same and may have different behaviors for certain edge cases.
Just remember, readability and code intention are essential when deciding to use the
Although it is faster and takes less space than some alternatives, using more explicit functions like
parseInt() can make the code easier to understand for others.
Balancing performance and readability is tricky but important in writing efficient and maintainable code. ⚡️