includes()

ES7+

Determines whether an array includes a certain value among its entries.

Syntax

array.includes(searchElement, fromIndex)

Parameters

searchElement any

The value to search for

fromIndex number optional

Position to start searching from

Return Value

boolean

true if the value is found, otherwise false

Examples

JavaScript
const fruits = ['apple', 'banana', 'cherry'];
console.log(fruits.includes('banana'));
console.log(fruits.includes('mango'));
Output:
// true false

📌 When to Use

Use includes() for simple membership tests with primitive values. It's the clearest way to check if an array contains a specific value, especially when you don't need the index or the element itself.

⚠️ Common Mistakes

Using includes() with objects - it uses strict equality (===), so object references must match exactly

Forgetting that includes() can find NaN (unlike indexOf())

Using indexOf() !== -1 when includes() would be more readable

✅ Best Practices

Use includes() for cleaner code: arr.includes(val) instead of arr.indexOf(val) !== -1

For object lookups, use some() with a custom comparison function instead

Combine with Set for frequent lookups: new Set(arr).has(val) is O(1)

⚡ Performance Notes

includes() is O(n) for arrays - it checks each element until it finds a match. For frequent membership tests on large arrays, convert to a Set first for O(1) lookup time. Unlike indexOf(), includes() correctly identifies NaN.

🌍 Real World Example

Checking User Roles for Access Control

Verify if a user has a specific role before showing admin features

const userRoles = ['user', 'editor'];
const adminRoles = ['admin', 'superadmin'];

const isAdmin = adminRoles.some(role => userRoles.includes(role));
// isAdmin: false

// Simple feature flag check
const enabledFeatures = ['dark-mode', 'notifications', 'analytics'];
if (enabledFeatures.includes('dark-mode')) {
  enableDarkMode();
}

Related Methods