0

I wrote an if condition where the return value is the indexOf an array. The if condition is failing when the first object of the array is returned (index of which is 0). Is there any way to fix this?

I'm checking if the value term is present in the array.

My code is:

if (array.indexOf(term)) {
    //do something
}
else {
    alert("error");
}
David Sherret
  • 101,669
  • 28
  • 188
  • 178
pal
  • 105
  • 1
  • 3
  • 17
  • I'm guessing you're running into a null exception of some sort. [This question](http://stackoverflow.com/questions/218384/what-is-a-null-pointer-exception-and-how-do-i-fix-it) is in java, but it explains the same concept (just adapt it to javascript) – ryanyuyu May 07 '15 at 20:09
  • You are missing a closing parenthesis. Was that a copy/paste error? – Jason May 07 '15 at 20:10
  • 4
    if(array.indexOf(term)>-1) is the usual way. – Sidd May 07 '15 at 20:10
  • @Jason yeah a copy paste error. corrected it. – pal May 07 '15 at 20:11
  • @pal You fixed it wrong. The parenthesis belongs on the first line. – Barmar May 07 '15 at 20:14
  • Related question: http://stackoverflow.com/questions/28755645/indexof-with-if-statement-why-is-it-1-and-not-0 – Barmar May 07 '15 at 20:14

3 Answers3

3

This happens because 0 is falsy in JavaScript. Consider this sample:

if (0) {
    console.log("will never run");
}

That log() call will, as implied, never run.

You can do something like:

if(array.indexOf(term) > -1) { 
    // do stuff 
}

Or a more meaningful comparison, depending on context.

jdphenix
  • 15,022
  • 3
  • 41
  • 74
1

The indexOf() function returns the index of the element in the array. If it's not found, it will return a -1. Thus you must check if indexOf() returns a value greater than -1. If true, it is in the array.

Jason
  • 1,081
  • 10
  • 24
1

You can also use the bitwise NOT operator (~) to quickly check whether the index of something means it contains it or not. For instance...

if(~[].indexOf('no')) { // Evaluates to 0
    console.log('Bitwise NOT of -1 evalautes to true'); // It doesn't
} else if (~['test'].indexOf('test')) { // Evaluates to something other than 0
    console.log('Bitwise NOT of 0 evalautes to true'); // It does
}
Pluto
  • 2,900
  • 27
  • 38