In JavaScript, you can check if a value exists in an array using the indexOf() method or the includes() method, which are both available on the Array prototype.

The indexOf() method returns the first index at which a given element can be found in the array, or -1 if it is not present. For example:

var fruits = ["apple", "banana", "cherry"];
var isExist = fruits.indexOf("banana") !== -1;
console.log(isExist); // true

The includes() method returns a Boolean indicating whether an array includes a certain value among its entries, returning true or false. For example:

var fruits = ["apple", "banana", "cherry"];
var isExist = fruits.includes("banana");
console.log(isExist); // true

You can also use the find() method to check if a value exists in an array. The find() method returns the value of the first element in the array that satisfies the provided testing function. If not found, it returns undefined.

var fruits = ["apple", "banana", "cherry"];
var isExist = fruits.find(item => item === "banana") !== undefined;
console.log(isExist); // true

You can use any of the above methods to check if a value exists in an array in JavaScript.

Also Read:

Categorized in: