I am looking through some code that someone else have written and I noticed this strange javascript if syntax.. Basicly, it looks like this:
// This is understandable (but I dont know if it have relevance)
var re = new RegExp("^" + someVar + "_", "i");
// !!~ ??? What is this black magic?
if (!!~varA.search(re)) { ... }
This is one of those things that is hard to google.. Any Javascript gurues that can explain this?
Unary operators like that just need to be interpreted from right to left. ~
is the bitwise "not" operator, and !
is the boolean inverse. Thus, those three:
false
or true
)The ~
here is the trickiest. The "search" routine (I surmise) returns -1
when it doesn't find anything. The ~
operator turns -1
to 0
, so the ~
allows one to interpret the "search" return value as true
(non-zero) if the target is found, and false
(zero) if not.
The subsequent application of !
— twice — forces the result to be a true boolean value. It's applied twice so that the true
/false
sense is maintained. edit Note that the forced conversion to boolean is not at all necessary in this particular code; the normal semantics of the if
statement would work fine with just the result of the ~
operator.
Basically, .search
returns the position at which it finds the result, or -1
if it doesn't match. Normal people would just write:
if( varA.search(re) > -1)
But personally I'd just use:
if( varA.match(re))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With