JavaScript, Array Contains


How to check if Array Contains or Includes a value or string using JavaScript?

You’ll be making use of Array.prototype.indexOf and Array.prototype.includes method to check if an array contains a value.

Using IndexOf Method

indexOf method gives you the element index inside an Array. So, if the element exists inside the array the index returned will be greater than -1. Here is how you use indexOf to check if a value is found in an array.

function findIfExists(array, elementToFind){
  if(array.indexOf(elementToFind) > -1){
    return "Element found!!";
  } else {
    return "Element not found";
  }
}

console.log(findIfExists([1,2,3,4,5],14))
// Outputs : "Element not found"

Using JavaScript Array Includes Method

includes method returns true or false if the element is found or not found respectively. Let’s have a look at the code example:

function findIfExists(array, elementToFind){
  if(array.includes(elementToFind)){
    return "Element found!!";
  } else {
    return "Element not found";
  }
}

console.log(findIfExists([1,2,3,4,5],4))// Output : "Element found!!"