includes array method, the second is
indexOf. There are a few caveats for each so let’s look at each.
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.
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.
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.
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.