The includes() method in JavaScript is used to check if an array includes a certain element. It returns true if the array contains the element, and false otherwise. This method is useful for quickly checking the presence of an element in an array without needing to iterate over the entire array manually.
Syntax
array.includes(searchElement, fromIndex);
Parameters
Parameters | Descriptions |
---|---|
searchElement | The element to search for in the array. |
fromIndex (Optional) | The index at which to start searching for the element. If omitted, the search starts from index 0. |
Return Value
Return Type | Description |
---|---|
Boolean | true if the array contains the element, false otherwise. |
Example 1: Using includes() to Check for an Element
This code demonstrates how to use the includes() method to check if an array contains a specific element.
let numbers = [1, 2, 3, 4, 5]; console.log(numbers.includes(3)); // Output: true console.log(numbers.includes(6)); // Output: false
Example 2: Using includes() with fromIndex
You can specify the fromIndex parameter to start the search from a specific index.
let numbers = [1, 2, 3, 4, 5]; console.log(numbers.includes(3, 2)); // Output: true (search starts from index 2) console.log(numbers.includes(3, 3)); // Output: false (search starts from index 3)
Example 3: Using includes() with NaN
The includes() method can also be used to check for the presence of NaN in an array.
let array = [1, 2, NaN, 4, 5]; console.log(array.includes(NaN)); // Output: true
Supported Browsers
Chrome | Edge | Firefox | Opera | Safari |
---|---|---|---|---|
47 | 14 | 43 | 34 | 9 |