Check if an array includes a value/element in javascript.

This article is about how to check if an array includes a value in JavaScript.

To check if an items exits inside an array you can use the includes() method in JavaScript.

Using Array.includes() In JavaScript

The includes() methods in JavaScript determines whether an array includes certain value in an array. If found it return true else false.



Let see it with an example.

const pets = ['cat', 'dog', 'bat'];
// output : true
// output : false

Alternatively, you can also use indexOf() to check for certain item in an array.

Using Array.indexOf() in JavaScript

The indexOf() method, will check and return the index of a value in an array. If the value don't exits in the array it will return -1.



Lets understand it with an simple example.

const fruits = ["Banana", "Orange", "Apple", "Mango"];

const index = fruits.indexOf('Mango')
//Output : 3

const index = fruits.indexOf('Pineapple')
//Output : -1

These two are the methods to check if an array contains specific elements in JavaScript.

Related Topics:

3 ways to loop an array in JavaScript | Quick ways

Check If Multiple Values Exists In An Array Using JavaScript

💾 Recommended Articles