JavaScriptArrays
Array. prototype. includes()
Checks whether an array contains the given value.
- Returns
trueorfalse.- Changes the original
- No
Example
#JavaScript
const languages = ['HTML', 'CSS', 'JavaScript']
console.log(languages.includes('CSS'))
console.log(languages.includes('css'))
console.log([1, NaN].includes(NaN))Console
true
false
true
Definition and usage
#The includes() method returns true if the array contains a value equal to the given one, and false otherwise. It’s the simplest way to ask "is this item on the list?".
The comparison works like ===, with one exception: includes() can find NaN, which indexOf() can’t. Objects are compared by reference, so [{ a: 1 }].includes({ a: 1 }) returns false.
The second, optional argument lets you start the search from a given index.
Syntax
#Syntax
array.includes(searchElement)
array.includes(searchElement, fromIndex)Parameters
#searchElement
any value
The value to search for.fromIndex
optional
The index to start from. A negative value counts from the end.
Browser support
#Widely available
Works in all modern browsers, phones included. You can use it without worry.
- Chrome
- Edge
- Firefox
- Safari
Good practices
#- Letter case matters. When comparing text typed by a user, normalize it first, for example with
toLowerCase(). - For very frequent lookups in a large collection, a
Setand itshas()method are faster.
Related entries
#- Array.prototype.indexOf()Returns the index of the first occurrence of a value, or -1.
- Array.prototype.some()Checks whether at least one element matches a condition.
- String.prototype.includes()Checks whether a string contains the given piece of text. Returns true or false, and is case-sensitive.
- SetA collection of unique values: each value can appear in the set only once.
Spotted a mistake or missing an example? Write to us.