If you read the comments at the jQuery inArray
page here, there's an interesting declaration:
!!~jQuery.inArray(elm, arr)
Now, I believe a double-exclamation point will convert the result to type boolean
, with the value of true
. 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
statement:
if (!!~jQuery.inArray("one", arr)) { alert("Found"); }
Breakdown:
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 -2
.
~!!~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?
~jQuery.inArray()
is actually very useful - possibly even a very good reason why the search functions return-1
for failure (the only value whose two's complement is falsy). Once you've seen and understood the trick, I feel it is even more readable than!= -1
. – Amadan!!~
for anything. – Kirk Wollif (x != -1)
andif (~x)
to me, is that the former actually expresses what you intend to do. The latter expresses you wanting to do something else entirely ("please convert my 64-bit Number to a 32-bit integer, and check if bitwise NOT of that integer is truthy"), where you just happen to get the desired result in this one case. – JimmiTh>= 0
probably wasn't leet enough, so the more cryptic!!~
was used. – Yoshi