Array.includes()
The Array.includes() method in JavaScript is used to determine if an array contains a specified element. It returns true if the element is found, and false otherwise.
Syntax
</>
Copy
includes(searchElement)
includes(searchElement, fromIndex)
Parameters
| Parameter | Description |
|---|---|
searchElement | The element to search for in the array. |
fromIndex | Optional. The position in the array at which to begin the search. The default is 0. If the value is negative, the search starts from the end of the array. |
Return Value
The includes() method returns true if the specified element is found in the array, otherwise it returns false.
Examples
1. Checking for an Element in an Array
This example demonstrates how to check if an array contains a specified element.
</>
Copy
const fruits = ["apple", "banana", "cherry"];
console.log(fruits.includes("banana"));
console.log(fruits.includes("grape"));
Output
true
false
fruits.includes("banana")returnstruebecause “banana” is in thefruitsarray.fruits.includes("grape")returnsfalsebecause “grape” is not in thefruitsarray.
2. Using fromIndex Parameter
The fromIndex parameter specifies the position in the array at which to start the search.
</>
Copy
const numbers = [1, 2, 3, 4, 5, 6];
console.log(numbers.includes(3, 2));
console.log(numbers.includes(3, 4));
Output
true
false
numbers.includes(3, 2)returnstruebecause the search starts at index2, where the element3is located.numbers.includes(3, 4)returnsfalsebecause the search starts at index4, and the element3is not found beyond this index.
3. Case Sensitivity in includes()
The includes() method is case-sensitive, meaning it differentiates between uppercase and lowercase characters.
</>
Copy
const letters = ["A", "B", "C"];
console.log(letters.includes("a"));
console.log(letters.includes("A"));
Output
false
true
letters.includes("a")returnsfalsebecause “a” (lowercase) is not the same as “A” (uppercase).letters.includes("A")returnstruebecause “A” (uppercase) is in thelettersarray.
4. Using includes() with Negative fromIndex
A negative fromIndex value is interpreted as an offset from the end of the array.
</>
Copy
const colors = ["red", "green", "blue", "yellow"];
console.log(colors.includes("green", -3));
console.log(colors.includes("red", -2));
Output
true
false
colors.includes("green", -3)returnstruebecause the search starts three elements from the end, where “green” is located.colors.includes("red", -2)returnsfalsebecause “red” is not found when starting the search from two elements from the end.
