I was reading this blog post which mentioned using:
!!~
I have no idea what this does? at first I thought it would give an error, but the code below does run:
var _sessions = [
"_SID_1",
"_SID_2",
"_SID_3",
"_SID_4"
];
if(!!~_sessions.indexOf("_SID_5")) {
console.log('found');
} else {
console.log('!found');
}
output:
node test.js
!found
~is the bitwise not operator. It inverts the bits of its operand.!is the logical not operator. The bitwise not operator will return0when applied to-1, which is whatindexOfreturns when the value is not found in the array. Since0evaluates tofalse, doubly negating it will simply returnfalse(a boolean value, rather than a numeric one):The bitwise not operator will return a value less than 0 for any other possible value returned by
indexOf. Since any other value will evaluate totrue, it’s just a shorthand method (kind of… they are both the same number of characters!) of checking whether an element exists in an array, rather than explicitly comparing with-1:Update
With regards to the performance of this, it appears (in Chrome at least) to be marginally slower than the more common comparison with
-1(which itself is marginally slower than a comparison with0).Here’s a test case and here’s the results:
Update 2
In fact, the code in your question can be shortened, which may have been what the author was attempting to do. You can simply remove the
!!, since the~will always result in0or below (and0is the only value that will evaluate tofalse):However, in a slightly different situation it could make sense to add in the
!operators. If you were to store the result of the bitwise operator in a variable, it would be a numeric value. By applying the logical not operator, you get a boolean value (and applying it again ensures you get the correct boolean value). If for some reason you require a boolean value over a numeric one, it makes a little bit more sense (but you can still just use the normal comparison with-1or0):