Tell me more ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

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

share|improve this question
1  
if( ~that.indexOf('hello') ) is usually used – Esailija Jul 23 '12 at 19:02
2  
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

2 Answers

up vote 9 down vote accepted

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.

share|improve this answer
1  
That is neat, never seen that. – George Mauer Jul 23 '12 at 19:03
1  
@Florian MDN says: Inverts the bits of its operand. WTH does that mean? – iambriansreed Jul 23 '12 at 19:05
1  
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
7  
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
show 5 more comments

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.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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