This tutorial shows you how to check if a JavaScript array includes a value or not.
1. JavaScript Array.includes()
In JavaScript, there is a built-in array method called includes()
, that checks an array contains a certain value or not.
This method returns true
If the given value is present in the array, else it will return false
.
const fruits = ["Apple", "Banana", "Watermelon", "Pear", "Orange"]
const result = fruits.includes("Banana");
const result2 = fruits.includes("Grapes");
console.log(result)
console.log(result2)
true
false
2. JavaScript Array.indexOf()
You can use the Array.indexOf()
instead of includes()
. This method returns the first index number of the given item. But, if the given value does not present in the array, it will return -1
.
const fruits = ["Apple", "Banana", "Watermelon", "Pear", "Orange"]
const result = fruits.indexOf("Banana") !== -1;
const result2 = fruits.indexOf("Grapes") !== -1;
console.log(result)
console.log(result2)
true
false
This indexOf()
method is not for checking if a value exists in an array or not. Always use the includes()
method.
const fruits = ["Apple", "Banana", NaN]
const result = fruits.includes(NaN);
const result2 = fruits.indexOf(NaN) !== -1;
console.log(result)
console.log(result2)//❌ Not work
true
false
How to get the index number of the NaN value?
After seeing the above example, you may be wondering how to get the index number of a NaN
value.
So in JS, there is a method called Array.findIndex()
, you can use it to get the index number of the NaN value.
const fruits = ["Apple", "Banana", NaN]
const result = fruits.findIndex(Number.isNaN);
console.log(result)
2
3. Array.some() method
The Array.some()
method is almost similar to the findIndex()
method, but it returns a boolean value instead of the index number.
It will return true
If the given element is found in the array, else it will return false
.
const fruits = ["Apple", "Banana", "Watermelon", "Pear", "Orange", "Orange"]
const result = fruits.some(x => x === "Pear");
const result2 = fruits.some(x => x === "Mango");
console.log(result)
console.log(result2)
true
false
Apply the case insensitivity
const fruits = ["Apple", "Banana", "Watermelon", "Pear", "Orange", "Orange"]
const result = fruits.some(x => x === "pear");
const result2 = fruits.some(x => x.toLowerCase() === "pear"); // ✔️ Case insensitivity
console.log(result)
console.log(result2)
false
true