JavaScript - Array includes() Method
The JavaScript Array includes() method is used with the arrays to check if a particular element is present in the array. It returns a boolean value as a result: true if thr element is found in the array, and false if it is not present. This method is case sensitive for strings and checks for object references.
If we provide a negative "fromIndex" to this method, the search starts from backwards. For instance, -1 represents the last element.
Syntax
Following is the syntax of JavaScript Array includes() Method −
array.includes(searchElement, fromIndex);
Parameters
This method accepts two parameters. The same is described below.
- searchElement − The element that you are searching for in the array.
- fromIndex − The index in the array from which to start searching. If not specified, the search starts from the beginning of the array.
Return value
This method returns "true" if the search element is found in the array, else, "false".
Examples
Example 1
In the following example, we are using the JavaScript Array includes() method to search for the element "Dinosaur" in the specified array.
<html>
<body>
<p id="demo"></p>
<script>
const animals = ["Lion", "Cheetah", "Tiger", "Elephant", "Dinosaur"]
let result = animals.includes("Dinosaur");
document.getElementById("demo").innerHTML = result;
</script>
</body>
</html>
Output
After executing the program, the includes() method returns "true" as the element Dinosaur is present in the specified array.
true
Example 2
In the following example, we are searching for the element "Wolf" in the specified array −
<html>
<body>
<p id="demo"></p>
<script>
const animals = ["Lion", "Cheetah", "Tiger", "Elephant", "Dinosaur"]
let result = animals.includes("Wolf");
document.getElementById("demo").innerHTML = result;
</script>
</body>
</html>
Output
After executing the program, the includes() method returns "false" as the element "Dinosaur" is not present in the specified array.
false
Example 3
Here, we are checking if the specified array contains the element Elephant, starting from the index postion 2 −
<html>
<body>
<p id="demo"></p>
<script>
const animals = ["Lion", "Cheetah", "Tiger", "Elephant", "Dinosaur"]
let result = animals.includes("Elephant", 2);
document.getElementById("demo").innerHTML = result;
</script>
</body>
</html>
Output
The program returns true because the element "Elephant" is present after the index postion 2.
true
Example 4
Here, we are checking if the specified array contains the element "Cheetah", starting from the index postion 3 −
<html>
<body>
<p id="demo"></p>
<script>
const animals = ["Lion", "Cheetah", "Tiger", "Elephant", "Dinosaur"]
let result = animals.includes("Cheetah", 3);
document.getElementById("demo").innerHTML = result;
</script>
</body>
</html>
Output
The program returns "false" because the element "Cheetah" is present after the index postion 3.
false