# indexOf() + 1 vs indexOf() != -1 [closed]

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

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


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

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

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.

• That is neat, never seen that. – George Mauer Jul 23 '12 at 19:03
• @Florian MDN says: Inverts the bits of its operand. WTH does that mean? – iambriansreed Jul 23 '12 at 19:05
• 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) – Esailija Jul 23 '12 at 19:06
• @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. – Florian Margaine Jul 23 '12 at 19:07
• 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. – Sulthan Jul 24 '12 at 9:48

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.