suryanaga
suryanaga

Reputation: 4012

what does !~myVar do?

I'm trying to read this code:

  var cloneKeys = Object.keys(base).filter(function ( k ) {
    return !~noCloneKeys.indexOf(k);
  });

What does the !~ do here? I've never seen it before, and it's difficult to search. From the expressions and operators reference it looks like a combination of a logical operator and a bitwise operator, but that doesn't really make any sense to me.

Upvotes: 0

Views: 57

Answers (2)

Matt Way
Matt Way

Reputation: 33161

This is the combination of two operators not ! and tilde ~.

Tilde (bitwise Not) - ~:

This operator performs -(input + 1) (it actually is flipping bits, but I think that this is a nice beginner way to think about it). So in the case of indexOf(), which returns -1 if the input is not found, tilde will convert -1 to 0. For all cases where the input is found, tilde will convert a 0 or greater value to -1, -2, -3, -4, etc.

Not - !:

This is a boolean operator that inverts the input. Or in your case will invert any 0 to true, and any non zero to false.

So if we combine them, we are saying give me 0 for any instance where indexOf cannot find the input, and invert it to true. For all other valid inputs return false.

Upvotes: 1

Leon Adler
Leon Adler

Reputation: 3341

It is a (very unreadable) short form of noCloneKeys.indexOf(k) == -1.

~value = binary inverse, ~(-1) => 0
!value = boolean inverse, !(0) => true

To keep your fellow developers mentally sane, please write == -1 or < 0...


Detailed:

-1 == binary 11111111111111111111111111111111 (assuming 32 bit integer)
~(-1)   ==   00000000000000000000000000000000
!(~(-1)) == !(0) == true

Upvotes: 2

Related Questions