xeor
xeor

Reputation: 5455

Javascript - Weird if syntax

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?

Upvotes: 5

Views: 367

Answers (3)

Pointy
Pointy

Reputation: 413717

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.

Upvotes: 11

Johan
Johan

Reputation: 8256

In laymans terms

 ~ 

is doing -(N+1) and

!!

The first bang casts from the number to a Boolean, and the second undoes the logical not that was performed by the first bang.

Have a look at this website.
it has a few explanations

http://dreaminginjavascript.wordpress.com/2008/07/04/28/

Upvotes: 0

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324640

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))

Upvotes: 4

Related Questions