const array = ["Bento", "Burger", "Melon", "Burrito", "Burger"];array.includes("Burrito"); // will return truearray.indexOf("Burger"); // will return 1
includes() method checks to see whether an array contains a certain value among its elements. It will return either
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.
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
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
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 0strawHats.indexOf("Smoker"); // will return -1
Watch-outs for Includes and IndexOf
There are a few little caveats with the
indexOf methods that are important to be aware of when using them to see if a value is in an array.
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 falsestrawHats.includes("Nami"); // will return truestrawHats.indexOf("sanji"); // will return -1strawHats.indexOf("Sanji"); // will return 3
const lowerCaseArray = strawHats.map((item) => item.toLowerCase());strawHats.includes("nami"); // will return truestrawHats.indexOf("sanji"); // will return true
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
Also check can I use for more information.