ithinc
ithinc

Reputation: 83

What's the preferred operator when comparing indexOf result with -1, "!=" or ">"?

What's the preferred operator when comparing the result of indexOf with -1, "!=" or ">"? Is there any difference?

Upvotes: 2

Views: 326

Answers (3)

T.J. Crowder
T.J. Crowder

Reputation: 1074148

As Nick said, either is fine. I prefer >= 0 because then I'm coding a positive:

index = str.indexOf('foo');
if (index >= 0) {
    // Do something with `index`
}
else {
    // 'foo' wasn't found
}

Upvotes: 2

Martijn
Martijn

Reputation: 606

I would say !=. You said it yourself actually:

when comparing the result of indexOf with -1

Moreover, != is faster than >.

Upvotes: 1

Nick Craver
Nick Craver

Reputation: 630379

Either is ok here, you just care that it's not -1. Personally, I prefer !=, since I'm saying it's explicitly not something that way...and that's the check we're performing. For example:

if(arr.indexOf("thing") != -1)

It's checking explicitly for not that single value, the unique -1 result you get when it's not found. With >, you're checking for any other value...I find this more explicit, just use what's clearer for you.

Another reason I steer clear of > is that far too many times (in both questions and answers) on StackOverflow I see if(arr.indexOf("thing") > 0) which is almost never the correct check.

Upvotes: 5

Related Questions