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\$
3
  • 1
    \$\begingroup\$ if( ~that.indexOf('hello') ) is usually used \$\endgroup\$
    – Esailija
    Commented Jul 23, 2012 at 19:02
  • 3
    \$\begingroup\$ What's wrong with indexOf(...) >= 0? \$\endgroup\$ Commented Jul 23, 2012 at 20:48
  • \$\begingroup\$ @RussellBorogove Nothing. It's totally valid. ~ is a lot cleaner than >= 0. \$\endgroup\$ Commented Jul 23, 2012 at 21:07

2 Answers 2

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\$
9
  • 1
    \$\begingroup\$ That is neat, never seen that. \$\endgroup\$ Commented Jul 23, 2012 at 19:03
  • 2
    \$\begingroup\$ @Florian MDN says: Inverts the bits of its operand. WTH does that mean? \$\endgroup\$ Commented Jul 23, 2012 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
    Commented Jul 23, 2012 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\$ Commented Jul 23, 2012 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
    Commented Jul 24, 2012 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.