The includes() method checks if an array contains a specified element or not.
Example
includes() Syntax
The syntax of the includes() method is:
arr.includes(valueToFind, fromIndex)
Here, arr is an array.
includes() Parameters
The includes() method can take two parameters:
- searchValue- The value to search for.
- fromIndex (optional) - The position in the array at which to begin the search. By default, it is 0.
Note: For negative values, the search starts from array.length + fromIndex (Counting from backward). For example, -1 represents the last element.
includes() Return Value
The includes() method returns:
trueif searchValue is found anywhere within the arrayfalseif searchValue is not found anywhere within the array
Example 1: Using includes() method
Output
true false
In the above example, we have used the includes() method to check whether the languages array contains elements 'C' and 'Ruby'.
languages.includes("C") returns true since the array contains 'C' and languages.includes("Ruby") returns false since the array does not contain 'Ruby'.
Example 2: includes() for Case-Sensitive Search
The includes() method is case sensitive. For example:
Output
true false
Here the includes() method returns true for searchValue- 'Python' and false for 'python'.
This is because the method is case sensitive and it treats 'Python' and 'python' as two different strings.
Example 3: includes() with two Parameters
Output
false true
In the above example, we have passed two argument values in the include() method.
languages.includes("Java", 2) returns false since the method doesn't find 'Java' from second index of the array.
In languages.includes("Java", -3), the method starts searching 'Java' from the third last element because of the negative argument -3.
Recommended Reading: JavaScript Array indexOf()