JavaScript – Check if Array contains Specified Element
To check if an Array contains a specified element in JavaScript, call includes() method on this array and pass the element to search as argument to this method. includes() method returns true if the search element is present in this array, or else it returns false.
Examples
In the following script, we take an Array of Strings arr
, and check if the element 'banana'
is present in this array.
index.html
</>
Copy
<!DOCTYPE html>
<html lang="en">
<body>
<pre id="output"></pre>
<script>
var arr = ['apple', 'banana', 'cherry'];
var result = arr.includes('banana');
document.getElementById('output').innerHTML = 'Does array includes specified element? ';
document.getElementById('output').innerHTML += result;
</script>
</body>
</html>
Now, let us try to check if the element 'mango'
is present in the array arr
. Since, the specified element is not present in this array, includes() method must return false.
index.html
</>
Copy
<!DOCTYPE html>
<html lang="en">
<body>
<pre id="output"></pre>
<script>
var arr = ['apple', 'banana', 'cherry'];
var result = arr.includes('mango');
document.getElementById('output').innerHTML = 'Does array includes specified element? ';
document.getElementById('output').innerHTML += result;
</script>
</body>
</html>
Conclusion
In this JavaScript Tutorial, we have learnt how to use Array.includes() method to check if specified element is present in the array, with examples.