JavaScript includes() | Check if Value Exists in an Array

The JavaScript includes() method is used when we need to check whether an element or a value available in a specified array or not. For example:

HTML with JavaScript Code
<!DOCTYPE html>
<html>
<body>

   <p id="xyz"></p>
   
   <script>
      const arr = ["JavaScript", "is", "Fun"];
      let chk = arr.includes("is");
      if(chk)
         document.getElementById("xyz").innerHTML = "Element is available in the array";
      else
         document.getElementById("xyz").innerHTML = "Element is not available in the array";
   </script>
   
</body>
</html>
Output

JavaScript includes() Syntax

The syntax of includes() method in JavaScript, is:

array.includes(element, startingIndex)

The element is the value that is going to search in the array and startingIndex is the position/index from where we need to start searching the element.

The startingIndex parameter is optional.

The includes() method returns true if specified element exists in the specified array. Otherwise returns false. For example:

HTML with JavaScript Code
<!DOCTYPE html>
<html>
<body>

   <p id="abc"></p>
   
   <script>
      const myArray = ["Austin", "New York", "Seattle", "Boston", "San Diego"];
      let x = myArray.includes("New York");
      document.getElementById("abc").innerHTML = x;
   </script>
   
</body>
</html>
Output

Since the element or value New York is available in the array named myArray. Therefore the function includes() (myArray.includes()) returns true.

Now let me modify the above example to create another one, with startingIndex parameter:

HTML with JavaScript Code
<!DOCTYPE html>
<html>
<body>
   
   <p id="myPara"></p>
   
   <script>
      const ar = ["Austin", "New York", "Seattle", "Boston", "San Diego"];
      let res = ar.includes("New York", 2);
      document.getElementById("myPara").innerHTML = res;
   </script>
   
</body>
</html>
Output

Since indexing starts from 0, therefore index number 2 refers to the third element, that is Seattle.

JavaScript Online Test


« Previous Tutorial Next Tutorial »