What is Array.includes()?
The syntax of the
Array.includes() method is straightforward:
array: The array you want to search within.
searchElement: The element you want to find in the array.
fromIndex(optional): An optional parameter that specifies the starting index from which the search should begin. If omitted, the search starts from index 0. If
fromIndexis negative, it counts from the end of the array. If it's greater than or equal to the array's length, the method returns
falseas there is no element to search beyond that point.
Let's walk through some practical examples to demonstrate how you can use
Example 1: Basic Usage
const fruits = ['apple', 'banana', 'cherry', 'date']; console.log(fruits.includes('banana')); // true console.log(fruits.includes('grape')); // false
In this example, we have an array
fruits, and we use
Array.includes() to check if it contains the elements 'banana' and 'grape'. As expected, it returns true for 'banana' and false for 'grape'.
Example 2: Using fromIndex
You can also specify a starting index for the search using the optional fromIndex parameter. This can be helpful when you want to search for elements starting from a specific position within the array.
const numbers = [1, 2, 3, 4, 5]; console.log(numbers.includes(3, 2)); // true console.log(numbers.includes(3, 3)); // false
In this example, we search for the value '3' within the numbers array, starting from index 2 and then from index 3. As a result, the method returns true for the first search and false for the second.
Example 3: Searching for NaN
Array.includes() can be used to search for the presence of
NaN in an array. This is especially useful because standard equality checks like
=== don't work for
In this case, the method correctly identifies the presence of NaN within the values array.
Array.includes() is a handy method, there are a few points to keep in mind:
Strict Equality: The method uses strict equality (
===) to compare elements. This means it won't work as expected if you're searching for complex objects unless they reference the same object in memory.
Not Suitable for Complex Searches: If you need to perform more complex searches, such as
searching for objects with specific properties, you may need to use other methods like
Limited Browser Compatibility: While
Array.includes()is supported in modern browsers, it may not be available in older ones. Always check compatibility before using it in production code or consider using polyfills for compatibility.
Remember that while
Array.includes() is excellent for basic element searches, more complex scenarios may require other array methods or custom logic. Always consider the specific requirements of your project when choosing the right tool for the job. Happy coding!