DEV Community

Cover image for The tilde(~) operator: the secret weapon for efficient integer conversion
aniketcodes
aniketcodes

Posted on

The tilde(~) operator: the secret weapon for efficient integer conversion

In JavaScript, the tilde (~) is a bitwise NOT operator. It performs a bitwise NOT operation on its operand, which inverts the bits of the operand.

For example:

let x = 5;  // 00000000000000000000000000000101
let y = ~x; // 11111111111111111111111111111010
Enter fullscreen mode Exit fullscreen mode

It's important to note that the bitwise NOT operator only works on integers. If you try to use it on a non-integer value (such as a string or a floating-point number), it will be converted to an integer before the operation is performed.

The tilde operator can also be used as a shorthand for Math.floor() to round a number down to the nearest integer. For example:

let x = 5.7;
let y = ~~x;  // y is 5
Enter fullscreen mode Exit fullscreen mode

In this example, the double tilde operator ~~ rounds the number x down to the nearest integer, resulting in y being set to 5. This is equivalent to using the Math.floor() function.

Just be mindful with the size of your integers using the double NOT operator

// 10 digits
> parseInt(9999999999)
9999999999
> ~~9999999999
1410065407

// 9 digits
> parseInt(999999999)
999999999
> ~~999999999
999999999
Enter fullscreen mode Exit fullscreen mode

Top comments (4)

Collapse
 
zerodragon profile image
Zero Dragon • Edited

Just be mindful with the size of your integers using the double NOT operator

// 10 digits
> parseInt(9999999999)
9999999999
> ~~9999999999
1410065407

// 9 digits
> parseInt(999999999)
999999999
> ~~999999999
999999999
Enter fullscreen mode Exit fullscreen mode

But in general I use it when I have to do a simple parseInt from small integers

> ~~'20221220' === 20221220
true
Enter fullscreen mode Exit fullscreen mode
Collapse
 
aniketcodes profile image
aniketcodes

Thanks.Adding this to the post.

Collapse
 
gilfewster profile image
Gil Fewster

Nice tip. Might be worth noting that it’s not the most well-known operator in the JS universe, so it may reduce the readability of your code.

I’ve seen some approaches which use bitwise NOT but wrap it in a named function so the the purpose in context is clearer to anyone not familiar with the technique.

Collapse
 
aniketcodes profile image
aniketcodes

Yeah. Couldn't agree more on this, but it might be useful to land some good impressions as a coder.