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