Array Includes Method
includes() returns true if an array contains a given value and false if it does not. It is the clearest way to ask a yes-or-no question about membership, which is why it has largely replaced the older indexOf(value) !== -1 test.
An optional second argument says which index to start searching from. A negative index counts back from the end, so -1 searches only the last element.
const allergens = ['milk', 'eggs', 'peanuts', 'soya'];
console.log(allergens.includes('eggs'));console.log(allergens.includes('Eggs'));console.log(allergens.includes('milk', 1));console.log(allergens.includes('soya', -1));This prints:
truefalsefalsetrueThe comparison of strings is exact, so 'Eggs' does not match 'eggs'. To ignore case, convert both sides, or use some() with a test that does.
How values are compared
Section titled “How values are compared”includes() compares values like === with one difference: it treats NaN as equal to NaN. indexOf() uses === strictly, so it cannot find NaN at all. Neither method converts types, so the string '5' does not match the number 5.
const readings = [3, NaN, 5];
console.log(readings.includes(NaN));console.log(readings.indexOf(NaN));console.log(readings.includes('5'));This prints:
true-1falseObjects are matched by reference
Section titled “Objects are matched by reference”An object is equal only to itself, so includes() finds an object only if you pass that same object. A new object with the same properties is a different object. To search by a property’s value, use some(), or find() to get the object back.
const users = [{ name: 'Asha' }, { name: 'Tom' }];
console.log(users.includes({ name: 'Asha' }));console.log(users.includes(users[0]));console.log(users.some((user) => user.name === 'Asha'));This prints:
falsetruetrueSteve Griffith covers this topic in his video JavaScript Array includes method.