Practical Tilde (~) Operator

As a JavaScript or Node developer who regularly codes, it is likely that you have encountered situations in which the usage of the tilde operator seems unclear. In this article, I aim to provide a clear explanation of its practical applications. I will explore several real-world use cases to provide a better understanding of the tilde operator and its functionality, so please continue reading.

It is important to note that the tilde operator is not the same as Math.floor, but it can exhibit similar behavior in certain situations. The tilde operator is a bitwise NOT operator, and its main function is to invert the bits of a number. It can also be used to quickly convert a positive number to its negative counterpart, or vice versa. It is not recommended to use tilde operator instead of Math.floor, as they are different and have different use cases.

Math.floor( 2.3 ) // 2
~~( 2.3 ) // 2

Math.floor( -4.5 ) // -5
~~(-4.5) // -4

I would be happy to share some of my tricks for faster programming that make use of the tilde operator.

One way I utilize the tilde operator is to remove the fractional part of the result of multiplying a number with Math.random. The tilde operator can be used in this case as a shorthand method for quickly truncating decimal values, instead of using Math.floor or parseInt. It can be used like this:

const rand = (start, end) =>
    ~~(Math.random() * (end - start) + start)

Another example of how I use tilde operator is to check if an element is present in an array, before the Array.prototype.includes() method was introduced in ECMAScript 2016.

const names = ["John", "Jane", "Jeff", "Jack"]
if(~names.indexOf("Jake")) {
    console.log("Jake is present")
} else {
    console.log( "Jake is absent!" )
}

// Jake is absent!

Another use case for the tilde operator is to extract the integer value from a string and verify that there are no other alphabetical letters present. The tilde operator can be used to quickly convert the result of parseInt to a negative value if it’s not a valid number. It can be used like this

const myString = "23abc";
const myNumber = parseInt(myString);
if (~myNumber) {
   console.log("The string contains a valid number: " + myNumber);
} else {
   console.log("The string does not contain a valid number.")
}