JavaScript array includes(): Check if a value exists in an array

The JavaScript includes() method is used when we need to check whether an element or a value is 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 the includes() method in JavaScript is:

array.includes(element, startingIndex)

The element is the value that is going to be searched in the array, and startingIndex is the position or index from which we need to start searching the element.

The startingIndex parameter is optional.

The includes() method returns true if the specified element exists in the specified array. Otherwise, it 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 the 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, index number 2 refers to the third element, which is Seattle.

JavaScript Online Test


« Previous Tutorial Next Tutorial »


Liked this post? Share it!