const array = ["Bento", "Burger", "Melon", "Burrito", "Burger"];
array.includes("Burrito"); // will return true
array.indexOf("Burger"); // will return 1
Check If An Array Contains a Value with the JavaScript Includes Method
The includes()
method checks to see whether an array contains a certain value among its elements. It will return either true
or false
.
The method can take two arguments. The first is the element you want to check for in the array. The second is fromIndex
which is the position in the array you want to start searching for an element, its default value is 0.
The fromIndex
is useful if you want to check only a certain portion of an array contains a value. It might be useful if say you wanted to check if Lebron James has had a 30 point game in his last 5 games.
const lebronPoints = [30, 19, 24, 25, 18, 23, 21, 25, 24, 29];
lebronPoints.includes(30, -5); // will return true
Check If An Array Contains a Value with the JavaScript indexOf method
The indexOf()
method checks to see if an array contains a value, that is does it exist in the array. If that value is in the array then it returns the index of the value, otherwise if the value is not found it will return -1.
Just like the includes
method it takes the searchElement
an fromIndex
arguments. The first argument is the value you want check if it exists in the array. The second argument which is optional, is the position in the array you want to start searching for an element from.
const strawHats = ["Zoro", "Nami", "Usopp", "Sanji"];
strawHats.indexOf("Zoro"); // will return 0
strawHats.indexOf("Smoker"); // will return -1
Watch-outs for Includes and IndexOf
There are a few little caveats with the includes
and indexOf
methods that are important to be aware of when using them to see if a value is in an array.
Case sensitivity
Both of the methods are case sensitive, meaning you if you search an array for a value it has to match the case exactly. Let's look at the strawHats
array to give us a better idea of what to watch out for.
strawHats.includes("nami"); // will return false
strawHats.includes("Nami"); // will return true
strawHats.indexOf("sanji"); // will return -1
strawHats.indexOf("Sanji"); // will return 3
To ensure we can check if array contains value in JavaScript we can make the array case insensitive.
const lowerCaseArray = strawHats.map((item) => item.toLowerCase());
strawHats.includes("nami"); // will return true
strawHats.indexOf("sanji"); // will return true
Browser Support
Like many awesome newer methods IE does not support them (booo IE). However, modern browsers love includes
so you can use it if you're not planning on supporting IE, otherwise you'll need to use indexOf
.
Also check can I use for more information.