1

This will be needed later on: elementStr = 'hello'.

So I am working on an javascript app. In one of my function I have a following if statement:

if (elementStr.indexOf('#') !== 0) {
        //true
    } 

But I don't like the !== part it doesn't look nice to me. So I tried this:

if (!elementStr.indexOf('#')) {
        //false
    } 

But indexOf() does not return undefinied but it always returns a number. So the first if statement returns true because elementStr does not have a '#' in the first place of the string. But the second if statement returns false because indexOf returns -1 and thats not 'undefined', but we want it to return true of course like the first example. Because we don't want to change the statement, we just want to make it look better. So by accident I did this:

if (!~elementStr.indexOf('#')) {
    //true
} 

And gues what, it worked. I tried to find something about that sign, what it does in javascript. But i couldn't find anything. I was playing with it and I got following results:

if (!~~elementStr.indexOf('#')) {
    //false
} 

if (!~~~elementStr.indexOf('#')) {
    //true
} 

You can go on and add ~ everytime, and the statement boolean will change all the time.

Now can someone explain me what it does in this example, and if I am safe to use that sign?

Johnny
  • 161
  • 3
  • 11
  • 3
    *if I am safe to use that sign* — You don't know what it does. Lots of other people won't know what it does. Using it makes the code much less clean than `!==`. Don't use it for this. – Quentin Apr 28 '13 at 12:34
  • Drat, I meant to say "clear" not "clean". – Quentin Apr 28 '13 at 12:40

1 Answers1

3

Bitwise Operators

~a

Performs the NOT operator on each bit.

Example:

9 (base 10) = 00000000000000000000000000001001 (base 2)

~9 (base 10) = 11111111111111111111111111110110 (base 2) = -10 (base 10)

Community
  • 1
  • 1
CD..
  • 72,281
  • 25
  • 154
  • 163