Question

In javascript the tilde operator is a bitwise NOT or complement, so why does the following not work as expected?

var x = true;
var tildeX = ~x;
var exclX = !x;


tildeX == exclX; // returns false
Était-ce utile?

La solution

The reason is because true is equivalent to 1, and when you perform a bitwise NOT (~) on the number 1 you get -2. Which when combined with the NOT operator (!) will produce false (because the only number that will produce true when combined with the NOT operator is 0)

Here is some information that you might find interesting

Quoted from the link:

Bitwise NOTing any number x yields -(x + 1)

Autres conseils

~ is a bitwise operation:

~(true) = ~1 = 0b11111110 (with 8bit character)

! is boolean negation:

!(true) = !1 = 0b00000000

x is not a boolean type and therefore has a load of leading bits set to zero.

~x will convert all those leading bits to 1. Therefore it will be non-zero.

!x, on the other hand, is zero.

That's why tildeX == exclX compares false.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top