JavaScript Reference ยท Array
JavaScript Array includes() method
Reference for JavaScript Array includes(): check whether an array contains a value, how NaN and objects compare, the fromIndex argument and examples.
The includes() method checks whether an array contains a given value and returns true or false. It compares with the "same-value-zero" rule: like ===, except that NaN is considered equal to NaN.
Use it for simple membership tests such as allowed.includes(role). For conditions ("any user older than 18?"), use some() or find() instead.
["a", "b"].includes("b"); // true
Try it
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Syntax
includes(searchElement) includes(searchElement, fromIndex)
| Name | Description |
|---|---|
searchElement |
The value to look for. |
fromIndex |
Optional. Index at which to begin the search, default 0. A negative value counts from the end (length + fromIndex), and if that is still below 0, the search starts at 0. |
Return value: true if the value was found, otherwise false.
Exceptions: none for ordinary arrays.
Usage notes
- Strict comparison.
1and"1"are different. Objects, arrays and functions are compared by reference, so[{ id: 1 }].includes({ id: 1 })isfalse. Search objects withsome(). NaNworks. UnlikeindexOf(),includes()findsNaN.+0and-0are treated as equal.- Holes count as
undefined.[ , ].includes(undefined)istrue, whileindexOf(undefined)skips holes and returns-1. - Case matters for strings:
"Editor"does not match"editor". Normalize first if you want a case-insensitive check. - Prefer it over
indexOf(x) !== -1. It says what you mean and handlesNaN. UseindexOf()only when you need the position. - Large lists: each call scans the array, so many lookups in a loop are O(nยฒ). Build a
Setand useset.has(x)for repeated checks. - Strings have their own
includes()for substrings; it is a different method with different semantics.
Browser support
includes() is supported in current browsers. It is newer than indexOf(), so check a compatibility table if you support very old environments.