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

Tell us what’s happening:

Describe your issue in detail here.

Your code so far

function quickCheck(arr, elem) {
  // Only change code below this line
if(arr.indexOf(elem)){
  return true
}else{
  return false
}
  // Only change code above this line
}

Why does truth appear? if there should be no

You appear to have created this post without editing the template. Please edit your post to Tell us what’s happening in your own words.

what is the output of indexOf?

outputs true, but should be false

no, indexOf outputs a number, which is the index of the thing you are searching or -1 if not present in the array

Also, be aware that 0 is considered a falsy value.

function indexOfCheck(arr, elem) {
  if (arr.indexOf(elem)) {
    return true;
  } else {
    return false;
  }
}

function includesCheck(arr, elem) {
  if (arr.includes(elem)) {
    return true;
  } else {
    return false;
  }
}

console.log(indexOfCheck(["firstElement"], "firstElement")); // false
console.log(includesCheck(["firstElement"], "firstElement")); // true

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.