Keisha Perkins Keisha Perkins - 1 month ago 6
Javascript Question

Checking if an array contains a value? (I've tried some techniques but I'm still a bit lost)

I am a beginner at JavaScript (beginner as in studying for about a week) and I'm stuck on how I can check if an array contains a certain string. Here I've made a word-guessing game.

I declare the

function
'contains' like this:

function contains(thing, array){
if(thing in array){
return true;
}
else {
return false;
}
};


I'm not sure what I'm doing wrong, but the value is always false.

The function uses the third technique here. But I've also tried using the accepted technique here, both with the same result.

Any help is greatly appreciated!

Answer

Had to make a separate answer to make sure this is clear. The correct approach to see if something is in an array:

var myArr = ['apples', 'bananas', 'pears'];

if (myArr.indexOf('pears') > -1) { // myArr.indexOf('pears') will equal the number 2
    console.log('we got pears'); // this will log
}

if (myArr.indexOf('hotdogs') > -1) { // since it's not in the array, it's -1
    console.log('hotdog!'); // this will not log
}

Finally please note that a for...in loop actually should not be used to iterate over arrays -- it really exists to iterate over keys in an object. For iterating over arrays in JS, a classic for loop is the correct approach.