1

I see sometimes the symbol ~ in code. I tried it with ~1, and it shows 0. And thus, I can see some code using this trick:

if ( !~text.indexOf('a') ){ }

To check for truthy value. Is it kind of bit shifting?

p.s.w.g
  • 146,324
  • 30
  • 291
  • 331
Naughty.Coder
  • 3,922
  • 7
  • 32
  • 41

3 Answers3

3

It's the bitwise NOT operator. It will convert the operand to an 32-bit integer, then yields one's complement (inverts every bit) of that integer.

Finally, ! will return true if and only only if the result of that operation is 0.

Some examples might help:

  x |   x (bin) | ~x (bin)  |  ~x |   !~x
 -3 | 1111…1101 | 0000…0010 |   2 | false
 -2 | 1111…1110 | 0000…0001 |   1 | false
 -1 | 1111…1111 | 0000…0000 |   0 |  true
  0 | 0000…0000 | 1111…1111 |  -1 | false
  1 | 0000…0001 | 1111…1110 |  -2 | false

In other words,

if ( !~text.indexOf('a') ) { }

is equivalent to:

if ( text.indexOf('a') == -1 ) { }
p.s.w.g
  • 146,324
  • 30
  • 291
  • 331
0

~ is the bitwise negation operator[MDN]. It converts its operand to a 32-bit integer and swaps all the 1s to 0s and all the 0s to 1s.

For example:

0000 0000 0000 0000 0000 0000 0000 0000 = 0
1111 1111 1111 1111 1111 1111 1111 1111 = ~0 = -1

Instead of doing text.indexOf(str) !== -1) you can use the tricky !~text.indexOf(str), because ~1 === 0 and !0 === true.

Peter Olson
  • 139,199
  • 49
  • 202
  • 242
0

~ is the unary negation operator. Basically converts the operand to a 32-bit integer and then flips every bit of the integer.

~12 =
~(00000000 00000000 00000000 00001100) =
 (11111111 11111111 11111111 11110011) =
-13
6502
  • 112,025
  • 15
  • 165
  • 265