Basic Data Structures: Check For The Presence of an Element With indexOf() question

Hello. I have this code:

function quickCheck(arr, elem) {
  // change code below this line
if(arr.indexOf(elem)) {
  return true;
else if(arr.indexOf(elem) === -1){
  return false;
  // change code above this line

// change code here to test different cases:
console.log(quickCheck(['squash', 'onions', 'shallots'], 'mushrooms'));

I get errors:

quickCheck(["squash", "onions", "shallots"], "mushrooms")

should return

quickCheck(["onions", "squash", "shallots"], "onions")

should return

quickCheck([true, false, false], undefined)

should return


Any ideas why my code does not work?

when indexOf returns 0 this will not execute because 0 is a falsy value

1 Like

array.indexOf(item) return index of item or -1 if item is not found
but -1 is not a falsy value in javascript
arr.indexOf(elem) is always true : your function return always true (except if item is at index 0 the function return undefined)

If you don’t care what the found index is, use arr.includes(item) and not indexOf. It just returns true or false as you’d expect.

Thanks for your replies.