How to use the Double Tilde (~~) Operator In Javascript

You can use the double tilde (~~) operator in JavaScript to convert NaN to 0. The double tilde is a bitwise operator that performs a bitwise NOT operation twice, effectively converting non-numeric values to 0.

Example: In this example, the variable value is assigned the value NaN. The ~~ operator is then used to convert NaN to 0, and the result is stored in the variable result. Finally, the console.log statement prints the result, which will be 0.

Javascript




let value = NaN;
let result = ~~value;
 
console.log(result); // Output: 0


Output

0


How to convert NaN to 0 using JavaScript ?

NaN (Not a Number) is usually used to indicate an error condition for a function that should return a valid number but it can be converted to 0 using JavaScript. We will discuss how to convert the NaN to 0.

Below are the approaches used to convert NaN to 0 using JavaScript:

Table of Content

  • Using isNaN() method
  • Using || Operator
  • Using ternary operator
  • Using Strictly Equality(===) operator
  • Using the Double Tilde (~~) Operator

Similar Reads

Using isNaN() method

The isNan() method is used to check whether the given number is NaN or not. If isNaN() returns true for “number” then it assigns the value 0....

Using || Operator

...

Using ternary operator

If “number” is any falsy value, it will be assigned to 0....

Using Strictly Equality(===) operator

...

Using the Double Tilde (~~) Operator

Here the number is checked via ternary operator, similar to 1, if NaN it converts to 0....