Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript - Weird if syntax

Tags:

javascript

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?

like image 575
xeor Avatar asked Sep 02 '13 13:09

xeor


2 Answers

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:

  • convert the return value to an integer
  • invert the bits of the integer
  • inspect the number for "truthiness" (zero or non-zero, false or true)
  • invert the boolean value
  • invert it again

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.

like image 148
Pointy Avatar answered Sep 26 '22 13:09

Pointy


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))
like image 31
Niet the Dark Absol Avatar answered Sep 23 '22 13:09

Niet the Dark Absol