Do You Know The ~~ Shorthand?

Do You Know The ~~ Shorthand?

·

2 min read

I've been working on coding challenges daily for a while now, and I'm always discovering new ways to solve problems, new tricks, and shorthand techniques. Recently, I came across this handy shorthand for Math.floor() and it totally, wait for it, floored me. (Lol)

What is the Shorthand

console.log( Math.floor(123.456789) ) //123
console.log( ~~123.456789 ) //123

So in JavaScript, the ~~ can be used as a shorthand for Math.floor() which is used to round down a decimal number to the nearest integer. The ~~ operator is actually a double bitwise NOT operator, which essentially performs two NOT operations on the number, effectively returning the same result as Math.floor().

"Huh? The NOT operator, you say?"

The NOT operator (~) inverts the bits of a number, effectively flipping all the bits from 0 to 1 and vice versa. When you apply the NOT operator twice (~~), it reverts the bits back to their original state, effectively returning the original number.

It is commonly used as a faster alternative to Math.floor() method because the bitwise operator is generally faster than the Math.floor() method, so it can be a good option for performance-critical code.

Shorthand for Number() too

Since the ~~ effectively returns the floored number, it can also be used when you want to convert a string value to an integer.

console.log( Number("10") ) //10
console.log( ~~"10" ) //10

Caution

~~ can be used as a quick shorthand for Math.floor() for positive numbers. Keep in mind, though, that it doesn't give the same results for negative numbers. It simply truncates the decimal part as shown below:

~~5.5    // => 5  (same as Math.trunc(5.5) and Math.floor(5.5))
~~(-5.5) // => -5 (same as Math.trunc(-5.5) but NOT the same as Math.floor(-5.5), which would give -6 )

Conclusion

While it's cool to learn about the ~~ shorthand and have it in the knowledge bank, it's important to also consider the readability of your code when using it. As a developer, I prefer to have my code easy to read and understand, even if it takes a couple more lines (or words in the case of Math.floor()). In my experience, this saves a lot of pain while maintaining the code. Therefore, I don't see myself making much use of this shorthand.

P.S. The coding challenge where I discovered the shorthand: https://www.codewars.com/kata/57c15d314677bb2bd4000017