-3

I need help breaking this down. Here is the original code:

function hasTreat(treat) {
  const treatsArr = ['cookie', 'cake', 'muffin', 'pie', 'ice cream'];
  if (treatsArr.indexOf(treat) === true) {
    return true;
  }
  return false;
}
if (hasTreat("cookie")) { // You should have a cookie. 
  console.log("You have a cookie!");
} else {
  console.log("You have no cookie."); // This is wrong. You should have a cookie. 
}

I've modified it to this:

function hasTreat(treat) {
  const treatsArr = ['cookie', 'cake', 'muffin', 'pie', 'ice cream'];
  if (treatsArr.indexOf('cookie') === true) {
    return true;
  } else {
    return false;
  }
}
if (hasTreat('cookie')) { // You should have a cookie. 
  console.log("You have a cookie!");
} else {
  console.log("You have no cookie."); // This is wrong. You should have a cookie. 
}

What in the world am I not understanding here? It bugs me so much to think that something makes sense and to find out it doesn't "work". Help, please. Thanks, guys.

prasanth
  • 22,145
  • 4
  • 29
  • 53
NickPurry
  • 33
  • 1
  • 8

2 Answers2

0

The indexOf() method returns the first index at which a given element can be found in the array, or -1 if it is not present (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf).

So your check should probably be:

  if (treatsArr.indexOf(treat) >= 0) {
    return true;
  }
  return false;
Christophe L
  • 13,725
  • 6
  • 33
  • 33
0
if (treatsArr.indexOf('cookie') > -1) 

or

if (treatsArr.includes('cookie')) 
Saurav kumar
  • 407
  • 2
  • 5
  • 11