Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does `!!~` mean in javascript? [duplicate]

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?

like image 860
user717236 Avatar asked Feb 16 '12 18:02

user717236


People also ask

How do I duplicate a string in JavaScript?

JavaScript String repeat() The repeat() method returns a string with a number of copies of a string. The repeat() method returns a new string. The repeat() method does not change the original string.

Can you define a function twice in JavaScript?

functions are data in memory stack, so when you define another function with the same name, it overrides the previous one. Show activity on this post. Well obviously you're not meant to define the same function twice. However, when you do, the latter definition is the only 1 that applies.


1 Answers

There's a specfic reason you'll sometimes see ~ applied in front of $.inArray.

Basically,

~$.inArray("foo", bar) 

is a shorter way to do

$.inArray("foo", bar) !== -1 

$.inArray returns the index of the item in the array if the first argument is found, and it returns -1 if its not found. This means that if you're looking for a boolean of "is this value in the array?", you can't do a boolean comparison, since -1 is a truthy value, and when $.inArray returns 0 (a falsy value), it means its actually found in the first element of the array.

Applying the ~ bitwise operator causes -1 to become 0, and causes 0 to become `-1. Thus, not finding the value in the array and applying the bitwise NOT results in a falsy value (0), and all other values will return non-0 numbers, and will represent a truthy result.

if (~$.inArray("foo", ["foo",2,3])) {     // Will run } 

And it'll work as intended.

like image 172
Yahel Avatar answered Oct 14 '22 15:10

Yahel