includes()
includes<
T>(collection,value,fromIndex?):boolean
includes<
T>(collection,value):boolean
Checks if value is in collection.
Use array.includes() or Object.values().includes() directly instead.
Type Parameters
T: T
The type of elements in the array, or the object type.
Parameters
Overload 1:
collection: T[]
The collection to inspect.
value: T
The value to search for.
fromIndex?: number
The index to search from.
Overload 2:
collection: T
The collection to inspect.
value: T[keyof T]
The value to search for.
Returns: boolean
true if value is found, else false.
See Also
- Array.includes() - MDN
- Browser support - Can I Use
- Object.values() - MDN
- Browser support - Can I Use
Since
2.0.0
Also known as
contains (Effect) · includes (Lodash, es-toolkit, Remeda, Ramda) · ❌ (Radashi, Modern Dash, Antfu)
Example
const numbers = [1, 2, 3, 4, 5];
// ❌ Deprecated approach
const hasThree = includes(numbers, 3);
console.log(hasThree); // true
// ✅ Recommended approach (for arrays)
const hasThreeNative = numbers.includes(3);
console.log(hasThreeNative); // true
// ✅ Recommended approach (for objects)
const obj = { a: 1, b: 2, c: 3 };
const hasThreeObj = Object.values(obj).includes(3);
console.log(hasThreeObj); // true
How it works?
Checks if value is in collection.
Deprecated: Use array.includes() directly (ES2016).
Native Equivalent
// ❌ includes(arr, value)
// ✅ arr.includes(value)
Use Cases
Check element presence 📌
Check if a value exists in an array.
const roles = ["admin", "moderator", "user"];
roles.includes("admin");
// => true
Validate allowed values
Check if a value is in an allowlist.
const allowedTypes = ["image/png", "image/jpeg", "image/gif"];
allowedTypes.includes(file.type);
Check string contains substring
Verify if a string contains a specific substring.
const email = "user@example.com";
email.includes("@");
// => true
Check if a route requires authentication
Verify if the current route is in a list of protected routes. Fundamental pattern for auth guards in any SPA or server-side routing.
const protectedRoutes = ["/dashboard", "/settings", "/profile", "/admin"];
function requiresAuth(path: string): boolean {
return includes(protectedRoutes, path);
}
// In a router guard or middleware
if (requiresAuth(currentPath) && !user.isAuthenticated) {
redirect("/login");
}