How to Check If a Value Exists in an Array – JavaScript?

How to Check If a Value Exists in an Array – JavaScript?

Asked on October 31, 2018 in Javascript.
Add Comment


  • 1 Answer(s)

      The indexOf() method returns the index of the element inside the array if it is found, and returns -1 if it not found.

      This method is used to  check whether a given value or element exists in an array or not,like this:

    <script>
      var fruits = ["Apple", "Banana", "Mango", "Orange", "Papaya"];
      // Check if a value exists in the fruits array
      if(fruits.indexOf("Mango") !== -1)
    {
        alert("Value exists!")
      } else
    {
        alert("Value does not exists!")
      }
    </script>
    

      ES6 has introduced the includes() method to perform this task very easily. But, this method returns only true or false instead of index number,

    For ex:

    <script>
      var fruits = ["Apple", "Banana", "Mango", "Orange", "Papaya"];
      alert(fruits.includes("Banana")); // Outputs: true
      alert(fruits.includes("Coconut")); // Outputs: false
      alert(fruits.includes("Orange")); // Outputs: true
      alert(fruits.includes("Cherry")); // Outputs: false
    </script>
    
    Answered on October 31, 2018.
    Add Comment


  • Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.