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");
}