user717236 user717236 - 9 months ago 46
Javascript Question

How does !!~ (not not tilde/bang bang tilde) alter the result of a 'contains/included' Array method call?

If you read the comments at the jQuery

page here, there's an interesting declaration:

!!~jQuery.inArray(elm, arr)

Now, I believe a double-exclamation point will convert the result to type
, with the value of
. What I don't understand is what is the use of the tilde (
) operator in all of this?

var arr = ["one", "two", "three"];
if (jQuery.inArray("one", arr) > -1) { alert("Found"); }

Refactoring the

if (!!~jQuery.inArray("one", arr)) { alert("Found"); }


jQuery.inArray("one", arr) // 0
~jQuery.inArray("one", arr) // -1 (why?)
!~jQuery.inArray("one", arr) // false
!!~jQuery.inArray("one", arr) // true

I also noticed that if I put the tilde in front, the result is

~!!~jQuery.inArray("one", arr) // -2

I don't understand the purpose of the tilde here. Can someone please explain it or point me towards a resource?

Answer Source

The tilde operator isn't actually part of jQuery at all - it's a bitwise NOT operator in JavaScript itself.

See The Great Mystery of the Tilde(~).

You are getting strange numbers in your experiments because you are performing a bitwise logical operation on an integer (which, for all I know, may be stored as two's complement or something like that...)

Two's complement explains how to represent a number in binary. I think I was right.