Javascript

How to check if an array includes a value in JavaScript?

There are many methods to check if an array includes a value in Javascript. In this article, we are going to discuss some of those methods. so, without wasting time, let’s get started

Also Read: How to sort an Array by Date in Javascript

Using indexOf() method to check if an array includes a value

We can use the indexOf() method in Javascript to check whether a given value or element exists in an array or not. If the element is found in the array, the indexOf() method returns the index of the element and returns -1 if it not found. Let’s understand this with the following example:

var beasts = ['ant', 'bison', 'camel', 'duck', 'bison'];

console.log(beasts.indexOf('bison'));
// expected output: 1

// start from index 2
console.log(beasts.indexOf('bison', 2));
// expected output: 4

console.log(beasts.indexOf('giraffe'));
// expected output: -1

Using includes() method to check if an array includes a value

With the release of Es6, we have one more method to check if an array includes a value by using the includes() method. includes() method returns only true or false based on the presence and absence of the element in the array. let’s understand this with an example:

var array1 = [1, 2, 3];

console.log(array1.includes(2));
// expected output: true

var pets = ['cat', 'dog', 'bat'];

console.log(pets.includes('cat'));
// expected output: true

console.log(pets.includes('at'));
// expected output: false

So, this is how you check if an array includes a value in Javascript. Thanks for reading!

Leave a Comment