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
  • 92,051
  • 24
  • 178
  • 169
pal
  • 105
  • 1
  • 3
  • 16

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
  • 14,226
  • 3
  • 39
  • 70
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
  • 971
  • 9
  • 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,612
  • 25
  • 34