5
\$\begingroup\$

When checking for existence of a substring I have been doing this:

var that = "ok hello cool";    
if( that.indexOf('hello') + 1 ) {
}

Instead of:

if( that.indexOf('hello') != -1 ) {
}

Am I overlooking something or is there a reason not to do this.

Update:

Yes, I was indeed unaware of the even simpler method of:

if ( ~that.indexOf( 'hello' ) ) {

}

You can read about the ~ bitwise operator and the other queer bitwise operators here: https://developer.mozilla.org/en/JavaScript/Reference/Operators/Bitwise_Operators

\$\endgroup\$
  • 1
    \$\begingroup\$ if( ~that.indexOf('hello') ) is usually used \$\endgroup\$ – Esailija Jul 23 '12 at 19:02
  • 3
    \$\begingroup\$ What's wrong with indexOf(...) >= 0? \$\endgroup\$ – Russell Borogove Jul 23 '12 at 20:48
  • \$\begingroup\$ @RussellBorogove Nothing. It's totally valid. ~ is a lot cleaner than >= 0. \$\endgroup\$ – iambriansreed Jul 23 '12 at 21:07
12
\$\begingroup\$

Here is the most seen way:

if ( ~that.indexOf( 'hello' ) ) {
}

The ~ operator does some magic and transforms only -1 in 0, thus it's the only falsy value.

\$\endgroup\$
  • 1
    \$\begingroup\$ That is neat, never seen that. \$\endgroup\$ – George Mauer Jul 23 '12 at 19:03
  • 2
    \$\begingroup\$ @Florian MDN says: Inverts the bits of its operand. WTH does that mean? \$\endgroup\$ – iambriansreed Jul 23 '12 at 19:05
  • 1
    \$\begingroup\$ Ok, that's not really important to understand here. All you need to understand is that ~-1 === 0 (false for not found) and ~anythingelse !== 0 (true for found) \$\endgroup\$ – Esailija Jul 23 '12 at 19:06
  • \$\begingroup\$ @iambriansreed It's working on the bits of the number. For example, 2 in base 10 is 0010 in base 2. Well, ~ inverts all the bits. But yeah, as Esailija says, it's not really important to know, you probably won't ever use it except for this case. \$\endgroup\$ – Florian Margaine Jul 23 '12 at 19:07
  • 9
    \$\begingroup\$ I think that this not the best way to make code readable. Why using bitwise operator to create a condition? != -1 is used in many languages and it is the simplest and most readable method. \$\endgroup\$ – Sulthan Jul 24 '12 at 9:48
13
\$\begingroup\$

Well, I believe the second one is more obvious what's going on...

if( that.indexOf('hello') != -1 ) {
}

That's all to it however, both expressions are valid and perfectly ok.

\$\endgroup\$

Not the answer you're looking for? Browse other questions tagged or ask your own question.