Array.prototype.includes()
The reason it exists: indexOf uses strict equality and therefore can never find NaN. includes uses SameValueZero and can.
Demo
A plain boolean answer — no index to interpret and no -1 to remember. An empty array is always false. The interesting behaviour is not visible with numbers from a text box: includes compares with SameValueZero, which behaves exactly like === except that it considers NaN equal to itself. That one difference is the entire reason the method was added.
Parameters
| Name | Type | Required | Description |
|---|---|---|---|
| searchElement | any | yes | Value to look for. Compared with SameValueZero: like ===, except NaN equals NaN. |
| fromIndex | number | no (0) | Index to start from. Negative counts from the end. |
Return value
boolean — True if the array contains the value, compared with SameValueZero — which treats NaN as equal to itself.
Common patterns
if (allowed.includes(role)) { ... }
if (values.includes(NaN)) { ... }
if (['a', 'b', 'c'].includes(key)) { ... }
Examples
Pitfalls
[1, 2, 3].includes('2')
[1, 2, 3].includes(Number("2"))
[{id: 1}].includes({id: 1})
[{id: 1}].some(o => o.id === 1)
items.includes(x)
items.indexOf(x) !== -1
When to use
- A plain yes/no membership test
- Checking a value against a fixed allow-list
- Any search where NaN might be the value
- You need the POSITION → indexOf
- Matching objects by contents → some with a predicate
- Large arrays searched repeatedly → a Set, which is O(1)
Notes
FAQ
It reads as the question you are asking and returns a boolean, so there is no -1 to remember. It also finds NaN, which indexOf structurally cannot because it compares with strict equality and NaN !== NaN.
[NaN].includes(NaN) // true [NaN].indexOf(NaN) // -1