JavaScript Array includes() method
The includes()
method in JavaScript is used to determine whether an array contains a specific element. It returns a boolean value: true
if the element is found in the array, and false
otherwise. This method is case-sensitive and can be particularly useful for checking membership in arrays.
Syntax:
searchElement
: The element to search for in the array.fromIndex
(optional): The index at which to begin the search. The default is0
. If the specified index is greater than or equal to the array's length, the search starts from the end of the array.
Return Value:
- A boolean value (
true
orfalse
):true
: If the specified element is found in the array.false
: If the specified element is not found.
Key Points:
- Case-sensitive: The search is case-sensitive for string elements.
- Searches the entire array by default: If
fromIndex
is not provided, the search starts from the beginning of the array. - Can find
NaN
: Theincludes()
method can accurately determine ifNaN
is present in the array (unlikeindexOf()
).
Example 1: Basic usage (Checking for a number)
Example 2: Searching with a starting index
Example 3: Element not found
Example 4: Searching for a string with case sensitivity
Example 5: Checking for NaN
Example 6: Using fromIndex
to search from the end
Summary:
- The
includes()
method provides a simple way to check if an element exists within an array, returningtrue
orfalse
based on its presence. - This method is useful for membership tests, as it can accurately find
NaN
and respects case sensitivity for strings. - The optional
fromIndex
parameter allows for customized searching, including the ability to start searching from a specific index.