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.

Syntax:

includes(searchElement)

Let see it with an example.

const pets = ['cat', 'dog', 'bat'];
console.log(pets.includes('cat'));
// output : true
console.log(pets.includes('rat'));
// 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.

Syntax:

indexOf(searchElement)

Lets understand it with an simple example.

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

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

const index = fruits.indexOf('Pineapple')
console.log(index)
//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