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
107k28 gold badges196 silver badges190 bronze badges
asked May 7, 2015 at 20:06
6
  • I'm guessing you're running into a null exception of some sort. This question is in java, but it explains the same concept (just adapt it to javascript) Commented May 7, 2015 at 20:09
  • You are missing a closing parenthesis. Was that a copy/paste error? Commented May 7, 2015 at 20:10
  • 4
    if(array.indexOf(term)>-1) is the usual way. Commented May 7, 2015 at 20:10
  • @Jason yeah a copy paste error. corrected it. Commented May 7, 2015 at 20:11
  • @pal You fixed it wrong. The parenthesis belongs on the first line. Commented May 7, 2015 at 20:14

3 Answers 3

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.

answered May 7, 2015 at 20:11

Comments

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.

answered May 7, 2015 at 20:12

Comments

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
}
answered May 7, 2015 at 20:22

2 Comments

I'm not sure if this is "fast" or "slow" in JavaScript but it's certainly valid
@jdphenix I guess instead of quick, I meant terse haha.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.