** Explanation Needed ** Check For The Presence of an Element With indexOf()

Link to challenge:

Solution:

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

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

or

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

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

“Modify the function using indexOf() so that it returns true if the passed element exists on the array, and false if it does not.”

Could someone please explain the solutions to me?

For the first solution, does >= 0 represents ‘mushrooms’ since is not within the array therefore it is -1, hence returning false?

If so, for the second solution, how does !== -1 work?

Hope my question is clear enough.

Thanks in advance!

!== means “not equal to”.
!== -1 will return true if the value on the left is not -1.

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