Learn more about the ~ operator in javascript.

Javascript Bitwise NOT , the ~ operator

~ Operator

This operator has a weird result when using with integers, it converts the integer value to - ( X + 1 ) value.

~2 === -3; //true
~1 === -2; //true
~0 === -1; //true
~-1 === 0; //true


// To explain you
// This is what the operator does to the given number

function bitwiseOperator(value){
  var result = Math.floor(value);
  // return the negative value of the result + 1;
  return - (result+ 1);
}


bitwiseOperator(2) === -3; //true
bitwiseOperator(1) === -2; //true
bitwiseOperator(0) === -1; //true
bitwiseOperator(-1) === 0; //true

However there are many developers that complains about the use of this operator as it makes the code "less readable", but seriously ... 

// A developer gets angry if see this
if (~[1,2,3].indexOf(2)) {
  console.log("The array contains 2");
}
// Explanation (if you don't understand ...)
/**
[1,2,3].indexOf(2) returns 1
and using ~ makes that 1 becomes : -2
Therefore -2 is truthy !
Remember : 0 is falsy , that's why this shortcut works as ~-1 == false;
*/

// but they don't get angry writing more
if ([1,2,3].indexOf(2) !== -1) {
  console.log("The array contains 2");
}
Comparing against !== -1 is the exact equivalent of verifying that the result was not -1 with ~, because :
var isNotInArray = ~-1; // 0 == false
var isInArray = ~0;// any index : 0 or 1 or 2 or 3 etc. : -1 == true
Only -1 is falsy after a tilde so indexOf result is truthy only when it's !== -1.

~~ Operator

The most practical way of utilizing the power of this operator is to use it as a replacement for Math.floor() function as double bitwise NOT performs the same operation a lot quicker.
~~2 === Math.floor(2); //true, 2
~~2.4 === Math.floor(2); //true, 2
~~3.9 === Math.floor(3); //true, 3

However, be careful with the negative numbers ! As you may notice undesired results :

var a = ~~-4.5; // -4
var b = Math.floor(-4.5); // -5
var c = Math.ceil(-4.5); // -4

(a == b) // false
(a == c) // true

With negative numbers, the ~~ operator, instead of work like Math.floor, seems to act as Math.ceil.


Although some developer doesn't like that , we doesn't agree with that point. Instead of complaining about how difficult is to read some code, you should be learning how it works without any kind of complaint. Also exist something called "comments" in the codes, to help with the reading.


Senior Software Engineer at Software Medico. Interested in programming since he was 14 years old, Carlos is a self-taught programmer and founder and author of most of the articles at Our Code World.

Sponsors