What is (~~) “double tilde” operator in JavaScript ?


The ~~ operator in JavaScript is known as the double tilde operator. It is a bitwise operator that performs a double NOT operation on a given number.

The double NOT operation converts the given number to a 32-bit signed integer. It first converts the number to a 32-bit binary representation, then performs a bitwise NOT operation on it, and finally performs another bitwise NOT operation on the result. This results in a number that is equivalent to the original number, but is guaranteed to be a 32-bit signed integer.

Here are some examples of using the double tilde operator in JavaScript:

Example 1:

let num = 3.14159;
let intNum = ~~num;
console.log(intNum); // Output: 3

In this example, the double tilde operator is used to convert the floating-point number 3.14159 to a 32-bit signed integer. The resulting value is 3.

Example 2:

let num = -5.6789;
let intNum = ~~num;
console.log(intNum); // Output: -5

In this example, the double tilde operator is used to convert the negative floating-point number -5.6789 to a 32-bit signed integer. The resulting value is -5.

Alternative method:

The double tilde operator can also be replaced with the Math.floor() method to achieve the same result. Here's an example:

let num = 3.14159;
let intNum = Math.floor(num);
console.log(intNum); // Output: 3

In this example, the Math.floor() method is used to convert the floating-point number 3.14159 to a 32-bit signed integer. The resulting value is 3.



About the author

William Pham is the Admin and primary author of Howto-Code.com. With over 10 years of experience in programming. William Pham is fluent in several programming languages, including Python, PHP, JavaScript, Java, C++.