What is the function of the ~ (tilde) operator in JavaScript?

33

I tried to search for Google and SOEN, but I did not find any reference to the ~ operator, I discovered that it exists, since I was reading a book about JavaScript and had an example using it, but the author also had not made any reference to the tilde before.

var i = 10;
var j = ~i;    // j = -11
var l = ~-i;   // l = 9
var x = ~true; // x = -2
var y = ~false;// y = -1

What is the function of the ~ operator and when is it usually used?

    
asked by anonymous 02.01.2014 / 22:03

2 answers

33

This is a binary denial operator, it operates by inverting a number bit by bit.

Simplified example

var x = 4; /* Em binário é representado como 100 */
var y = ~x; /* Agora o x invertido é representado como 011, ou seja, como o número -5,
               devido a negação complemento de 2 */

By using binary operators a 9 becomes 000000000 000000000 00000000 00001001 , becoming 11111111 11111111 11111111 11110110 , or -10, denied by the NOT operator binary ( ~ ).

Use

Even without much practical use it is possible to use the ~ operator to round down positive numbers by denying it twice:

var x = ~~93.4953; //93
var y = ~~94.9999; //94

This is because binary operators transform Number type, which by default is binary64 in 32-bit signed , which causes values after the comma to be ignored. p>

You can find more examples in MDN:

Bitwise Operators

    
02.01.2014 / 22:12
15

The ~ operator is the NOT binary operator (

02.01.2014 / 22:08